Java Basics (continued) Ms. Pack AP Computer Science A.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
CS 106 Introduction to Computer Science I 02 / 11 / 2008 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Fundamentals of Python: From First Programs Through Data Structures
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Java Basics (continued)
Fundamentals of Python: First Programs
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
DiceRoller DiceRoller (object class) and DiceRollerViewer client class: Write a DiceRoller class (similar to Yahtzee) to: Allow the person to initially.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Copyright © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30,
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Fundamentals of Java Text by: Lambert and Osborne Slides by: Cestroni.
4.1 Additional Operators Extended Assignment Operators –The assignment operator can be combined with the arithmetic and concatenation operators to provide.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Lesson 6 Selection Structures. Example program //This will convert a numeric grade into a letter grade import TerminalIO.KeyboardReader; public class.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
The Math Class Methods Utilizing the Important Math Operations of Java!
Lesson 4: Introduction to Control Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Introduction to Control Statements
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Lesson 4: Introduction to Control Statements 4.1 Additional Operators Extended Assignment Operators –The assignment operator can be combined with the.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Chapter 4 – C Program Control
Chapter 3 Syntax, Errors, and Debugging
Chapter 5: Control Structures II
Loop Structures.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Lecture 07 More Repetition Richard Gesick.
Selected Topics From Chapter 6 Iteration
LOOPS.
Lecture 4B More Repetition Richard Gesick
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Building Java Programs
IFS410 Advanced Analysis and Design
Let’s all Repeat Together
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Chapter 5: Control Structures II (Repetition)
Chapter 4 - Program Control
Review of Previous Lesson
Control Statements:.
Presentation transcript:

Java Basics (continued) Ms. Pack AP Computer Science A

Basic Java Syntax and Semantics Methods, Messages, and Signatures Classes implement methods, and objects are instances of classes. Objects that share common behavior are grouped into classes. An object responds to a message only if its class implements a corresponding method.  Messages are sometimes accompanied by parameters and sometimes not: pen.move(); // No parameter expected pen.moveDown(8); // One parameter expected Java Concepts 2.3 (Objects, Classes, and Methods), 2.4 (Method Parameters and return values)

Basic Java Syntax and Semantics Some methods return a value and others do not. To use a method successfully we must know:  What type of value it returns  It’s name (identifier)  The number and type of the parameters it expects This information is called the method’s signature. Java Concepts 2.3 (Objects, Classes, and Methods), 2.4 (Method Parameters and return values)

Basic Java Syntax and Semantics  Programming Protocols: Use camelCase  When forming a compound variable name, programmers usually capitalize the first letter of each word except the first. (For example: taxableIncome)  All the words in a class’s name typically begin with a capital letter (EmployeePayroll).  Constant names usually are uppercase and words are separated with underlines (INCOME_TAX_RATE). Java Concepts 2.1 (Types and Variables)

Comments Comments are explanatory sentences inserted in a program in such a matter that the compiler ignores them. There are two styles for indicating comments:  Single line comments: These include all of the text following a double slash (//) on any given line; in other words, this style is best for just one line of comments  Multiline comments: These include all of the text between an opening /* and a closing */ Java Concepts 1.6 (Compiling a Simple Program)

Additional Operators Extended Assignment Operators The assignment operator = can be combined with the arithmetic and concatenation operators to provide extended assignment operators. For example: int a = 9; String s = "hi"; a += 3; // Equivalent to a = a + 3; a -= 3;// Equivalent to a = a – 3; a *= 3;// Equivalent to a = a * 3; a /= 3;// Equivalent to a = a / 3; a %= 3;// Equivalent to a = a % 3; s += " there"; // Equivalent to s=s + " there"; Java Concepts 4.3 (Assignment, Increment, and Decrement)

Additional Operators Increment and Decrement Java includes increment (++) and decrement (--) operators that increase or decrease a variables value by one: int m = 7; double x = 6.4; m++; // Equivalent to m = m + 1; x--; // Equivalent to x = x – 1.0; The precedence of the increment and decrement operators is the same as unary plus, unary minus, and cast. Java Concepts 4.3 (Assignment, Increment, and Decrement)

Standard Classes and Methods Eight methods in the Math Class: Java Concepts 4.4 (Arithmetic Operations and Mathematical Functions) static double random()Returns a double in the range [0.0, 1.0)

Standard Classes and Methods Using the Math class double absNum, powerNum, randomNum, sqrtNum; absNum = Math.abs(-30); powerNum = Math.pow(-3, 3); randomNum = Math.random(); sqrtNum = Math.sqrt(25.0); Results: absNum has a value of 30.0//Absolute value of -30 powerNum has a value of -27.0//-3 to the 3 rd power randomNum has a value of ??? //Random number between //0 (inclusive) and 1 (exclusive) sqrtNum has a value of 5.0//Square root of 25.0 Java Concepts 4.4 (Arithmetic Operations and Mathematical Functions)

Standard Classes and Methods Random Numbers and Simulation The Random class of the Java library implements a random number generator. To generate random numbers, you construct an object of the Random class and then apply one of the following methods:  nextInt(n) – returns a random integer between 0 (inclusive) and n (exclusive) [0, n)  nextDouble() – returns a random floating point number between 0 (inclusive) and 1 (exclusive) [0, 1) For example, if a contestant on “Deal or No Deal” randomly selects their briefcase from the 26 initial briefcases: import java.util.Random; //Include this at top of program Random generator = new Random(); int briefcaseNum = generator.nextInt(26) + 1; Java Concepts 6.5 (Random Numbers and Simulation)

Control Statements while (some condition) { do stuff; } Do stuff repeatedly as long as the condition holds true if (some condition) { do stuff 1; } else { do stuff 2; } If some condition is true, do stuff 1, and if it is false, do stuff 2. While and if-else are called control statements. Java Concepts 5.1 (The if Statement), 6.1 (while Loops)

The if and if-else Statements Principal Forms In Java, the if and if-else statements allow for the conditional execution of statements. if (condition) { statement1; statement2; } if (condition) { statement1; statement2; } else { statement3; statement4; } Java Concepts 5.1 (The if Statement)

The if and if-else Statements Relational Operators The complete list of relational operators available for use in Java: Java Concepts 5.2 (Comparing values)

The if and if-else Statements Relational Operators Which of the following if statements are incorrect? int x; 1. if ( x > 10 ) 2. if ( x = 10 ) 3. if ( x >< 10 ) 4. if ( x == 10 ) 5. if ( x >= 10 ) 6. if ( x != 10 ) 7. if ( !x = 10 ) Incorrect Java Concepts 5.2 (Comparing values) Incorrect

The while Statement The while statement provides a looping mechanism that executes statements repeatedly for as long as some condition remains true. while (condition)// loop test statement;// one statement inside the loop body while (condition) // loop test { statement;// many statements statement;// inside the...// loop body } Java Concepts 6.1 (while Loops)

The while Statement Common Structure Loops typically adhere to the following structure: 1) initialize variables 2) while (condition) // perform test { 3) Loop body - perform calculations or do something 4) Loop body - change variables involved in the condition } In order for the loop to terminate, each iteration through the loop must move variables involved in the condition closer to satisfying the condition. Java Concepts 6.1 (while Loops)

The while Statement 1. Write a while loop that will sum the numbers from 1 to 100 (i.e … +100). 2. Print the answer to the console. Java Concepts 6.1 (while Loops)

The while Statement int sum = 0; int count = 1; while (count <= 100) { sum += count; count++; } System.out.println(sum); Java Concepts 6.1 (while Loops)

DiceRoller DiceRoller (object class) and DiceRollerViewer client class: Write a DiceRoller class (similar to Yahtzee) to: Allow the person to initially roll five dice. Each die has six faces representing numbers from 1 to 6, so the program should randomly pick a number between 1 and 6. Print the results of each die to the console. After the first roll, the person should input the number of dice (between 0 and 5) that they want to roll again.  If they enter 0, then don’t roll the dice again.  Else, roll that many dice and print the results of each die to the console again. Repeat the prompt one more time to see if the person wants to roll some of the dice again (for a maximum of 3 rolls). Write a DiceRollerGame client class to: Instantiate a DiceRoller object Run a method in DiceRoller (such as playGame() ) to play the game. EXTRA CREDIT (5 points): Have the player continue to take a turn (3 rolls) until they want to stop. HINT: You may want to use: the Scanner class to input data, the Random class to generate a random number to simulate rolling a die, a while loop for rolling each of the 6 dice, an if statement for checking the input, System.out.print for printing to the console. Java Concepts 6.5 (Random Numbers and Simulation)

The for Statement The for statement combines counter initialization, condition test, and update into a single expression. The form for the statement: for (initialize counter; test counter; update counter) statement; // one statement inside the loop body for (initialize counter; test counter; update counter) { statement; // many statements statement;// inside the...;// loop body } Java Concepts 6.2 (for Loops)

The for Statement Declaring the Loop Control Variable in a for Loop. The for loop allows the programmer to declare the loop control variable inside or outside of the loop header. The following are equivalent loops that show these two alternatives: int i; //Declare control variable above loop for (i = 1; i <= 10; i++) { System.out.println(i); } for (int i = 1; i <= 10; i++) //Declare var. in loop { System.out.println(i); } Use this technique if you need to reference the value of i later Use this technique if you only use variable i within the loop Java Concepts 6.2 (for Loops)

the break Statement The break statement can be used for breaking out of a loop early (before the loop condition is false). break statements can be used similarly with both for loops and while loops (break terminates the loop immediately). int sum = 0; for (int i = 1; i 100) break; } Java Concepts 6.4 Advanced Topic (break and continue Statements)

Nested Control Statements and the break Statement Control statements can be nested inside each other in any combination that proves useful. If you are nesting loops, the break statement only breaks out of the loop the program is currently in (the inside loop). int sum= 0; for (int i = 1; i 100) break; } System.out.println(“The sum is “ + sum); sum = 0; } Java Concepts 6.4 Advanced Topic (break and continue Statements) Breaks out of this loop (not the outside loop)

Sentinel A sentinel is a data value that is used to denote the end of a data list or data input. The value cannot be a valid data value Usually or an unreachable high value or it could be a character such as “Q” for Quit. Note: if you want the sentinel value to be “Q” then the value being entered needs to be a string. Example: Sum up the ages of your family members: int ageSum = 0; while (true) { System.out.println(“Enter age of family member (or 999 to quit)”); int age = in.nextInt(); if (age == 999) break; ageSum += age; } System.out.println(“Total age of all family members is “ + ageSum); Java Concepts 6.4 (Processing Sentinel Values)

Sentinel Write a segment of code that will have the user input their grades and print the average afterwards. The user should enter a sentinel value when there are no more grades to enter. Java Concepts 6.4 (Processing Sentinel Values)

Sentinel  Write a segment of code that will have the user input their grades and print the average afterwards. The user should enter a sentinel value when there are no more grades to enter. POSSIBLE OPTION: int sum = 0, numGrades = 0, grade; while (true) { System.out.print(“Enter a grade or 999 to end “); grade = in.nextInt(); if (grade == 999) break; sum += grade; numGrades += 1; } System.out.println(“Average is “ + (sum / numGrades ); Java Concepts 6.4 (Processing Sentinel Values) Missing parentheses Need to convert to a double Possible Divide by Zero error What bugs do you see in this line of code?

CircleCalc CircleCalc and CircleCalcViewer classes: Write a class to: Have the user input the diameter of a circle (floating point number) and the program outputs the:  Radius (how do you get the radius if you know the diameter?)  Circumference  Area  Note: you should use Math.PI in these calculations Use a sentinel controlled loop (sentinel value should be 99999) to keep asking the user the diameter of different circles. Test input for validity. EXTRA CREDIT (5 points): See next page What is the advantage of using a sentinel controlled loop? It allows the user to stop the looping whenever they want

CircleCalc Extra Credit (5 extra points) CircleComponent and CircleGraphicalViewer classes: Write classes to: In the client class, have the user input the diameter of a circle (floating point number) and instantiate a component object to:  Pass the diameter to a Component object  Calculate radius, circumference, and area ( Note: you should use Math.PI in these calculations)  Draw the circle in a frame and print the calculated values beside it. The diameter of the circle (in pixels) should match what the user entered. Use a sentinel controlled loop (sentinel value should be 99999) to keep asking the user the diameter of different circles. Test input for validity.