Lecture 2 Loops
Lecture 2 Loops
Lecture 2_a-2_b
System.out.printf
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012“
System.out.format("%,8d%n", n); // --> " 461,012“
System.out.format("%+,8d%n%n", n); // --> "+461,012"
double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593“
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // --> "3,1416"
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am“
System.out.format("%tD%n", c); // --> "05/29/06" }
}
https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf
WHAT HAPPENS WHEN WE RUN A CLASS…
When JVM starts running, it finds the selected class. Then it
starts looking for special method
//METHODS
Type methodname1 ( parameter_list ){
//body
} Member Methods
… (Things an object does)
Type methodnameN ( parameter_list ){
// body
}
}
EXAMPLE
public class Rectangle {
//two variables
public int breadth;
public int length;
//two methods
public void setLength(int newValue){
length =newValue;
}
public void setBreadth(int newValue){
Breadth= newValue;
}
}
RULES OF CLASS
Example:
char myFirstInitial;
System.out.println((double)byt);
}
}
JAVA CONSTANTS
Reminder: Constants are like variables in that they have a
name and store a certain type of information but unlike
variables they CANNOT change.
Format:
final <constant type> <CONSTANT NAME> = <value>;
Example:
final int SIZE = 100;
Why Use Constants?
It can make your program easier to maintain (update with
changes).
E.g.Value of PI
VARIABLE NAMING CONVENTIONS IN
JAVA
Compiler requirements
Can’t be a keyword nor can the names of the special constants: true, false or null
be used
Can be any combination of letters, numbers, underscore or dollar sign (first
character must be a letter or underscore)
Common stylistic conventions
The name should describe the purpose of the variable
Avoid using the dollar sign
With single word variable names, all characters are lower case
e.g., double grades;
Multiple words are separated by capitalizing the first letter of each word except
for the first word
e.g., String firstName = “James”;
JAVA KEYWORDS
implement
import instanceof int interface long native
s
Logical Operators
11 && Logical AND
Boolean variables Left to right true and
A holds
variable B holds false then
12 || Logical OR Left to right
(A && B) is false
(A || B) is true
!(A && B) is true
COMMON JAVA OPERATORS /
OPERATOR PRECEDENCE
Assignment Operators
x+=y is same as x=x+y
Precedence Operator Description x-=y is same as x=x-y
Associativity
level x%=y is same as x=x%y
13 = Assignment x|=y is same as x=x|y
Right to left
+= C <<= 2 is same as C = C << 2
Add, assignment
-= Subtract, assignment
*= Multiply, assignment
/= Division, assignment
%= Remainder, assignment
&= Bitwise AND, assignment
^= Bitwise XOR, assignment
|= Bitwise OR, assignment
<<= Left shift, assignment
>>= Right shift, assignment
POST/PRE OPERATORS
The name of the online example is: Order1.java
public class Order1
{
public static void main (String [] args) Output:
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
Fact:
}
} System.out.println inserts a newline (think of println as
print_new_line while if you want everything to stick
together on one line, use System.out.print).
POST/PRE OPERATORS (2)
The name of the online example is: Order2.java
public class Order2
{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5; OUTPUT
num2 =num1++ *++num; //5 * 7
System.out.println("num1=" + num1); num1=7
System.out.println("num2=" + num2); num2=35
}
}
UNARY OPERATOR/ ORDER/
ASSOCIATIVY
The name of the online example:Unary_Order3.java
Syntax:
import <Full library name>;
Example:
import java.util.Scanner;
GETTING TEXT INPUT
You can use the pre-written methods (functions) in the Scanner
class.
General structure:
import java.util.Scanner;
Creating a scanner
object (something
public static void main (String [] args) that can scan user
input)
{
Scanner <name of scanner> = new Scanner (System.in);
<variable> = <name of scanner> .<method> ();
}
Using the capability of the
scanner object (actually
getting user input)
Getting Text Input (2)
The name of the online example: MyInput.java
import java.util.Scanner;
public class MyInput
{
public static void main (String [] args)
{
String str1;
int num1;
Scanner in = new Scanner (System.in);
System.out.print ("Type in an integer: ");
num1 = in.nextInt ();
System.out.print ("Type in a line: ");
in.nextLine (); // consumes \n
str1 = in.nextLine ();
System.out.println ("num1:" +num1 +"\t str1:" + str1);
}
}
USEFUL METHODS OF CLASS
SCANNER1
nextInt ()
nextLong ()
nextFloat ()
nextDouble ()
nextLine ();
nextBoolean()
next();// accept a single word can read only till space
nextByte();
nextShort()
OR or ||
NOT not, ! !
DECISION MAKING : If
An if test is basically the same as the boolean test in a while
loop – except instead of saying,“while it is still raining”
you’ll say, “ if it is raining”
DECISION MAKING: if
class IfTest { X==3 Yes
if (playerNumber == WINNING_NUMBER)
System.out.println("You're a winner!");
else
System.out.println("Try again.");
}
}
DECISION MAKING : If, Else-If
Format: Is False? Then try next
if (Boolean expression) if
Body of if
else if (Boolean expression)
Body of first else-if Is False?
: : :
: : :
else if (Boolean expression)
Is False? Then run the
Body of last else-if
statements in else body
else
Body of else
DECISION MAKING : If, Else-If
DECISION MAKING : If, Else-If (2)
Name of the online example: BranchingExample.java
import java.util.Scanner;
case 'F':
case 'f':
gpa = 0;
break;
default:
gpa = -1;
}
System.out.println("Letter grade: " + letter);
System.out.println("Grade point: " + gpa);
}
}
Switch: When To Use/When Not To Use (4)
When a switch can’t be used:
For data types other than characters or integers
Boolean expressions that aren’t mutually exclusive:
As shown a switch can replace an ‘if-elseif’ construct
A switch cannot replace a series of ‘if’ branches).
Example when not to use a switch:
if (x > 0)
System.out.print(“X coordinate right of the origin”);
If (y > 0)
System.out.print(“Y coordinate above the origin”);
Example of when not to use a switch:
String name = in.readLine()
switch (name)
{
}
Switch Example: Modified
What happens if all the ‘break’ instructions have been
removed?
Output:
do while
While Loops
Format:
while (Boolean expression)
Body
Example: true
boolean
int i = 1; statement(s)
expression?
while (i <= 4)
{
// Call function
createNewPlayer();
i = i + 1; false
}
Infinite Loops
The loop runs infinite times if the value of i
is not decremented at each iteration :
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
x--;
}
4-55
While Loops (boolean test)
public class Loopy {
Example:
boolean true
statement(s) update
expression?
false
The for Loop Initialization
The initialization section of a for loop is optional; however, it is
usually provided.
Typically, for loops initialize a counter variable that will be
tested by the test section of the loop and updated by the
update section.
The initialization section can initialize multiple variables.
Variables declared in this section have scope only for the for
loop.
4-61
Multiple Initializations and Updates
The for loop may initialize and update multiple variables.
for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2)
{
statement(s);
}
Note that the only parts of a for loop that are mandatory
are the semicolons.
for(;;)
{
statement(s);
} // infinite loop
If left out, the test section defaults to true.
4-62
Do-While: Post-Test Loop
Recall: Post-test loops evaluate the Boolean expression
after the body of the loop has executed.
4-66
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
4-70
Sentinel Values
Sometimes the end point of input data is not known.
A sentinel value can be used to notify the program to stop acquiring
input.
If it is a user input, the user could be prompted to input data that is
not normally in the input data range (i.e. –1 where normal input
would be positive.)
Programs that get file input typically use the end-of-file marker to
stop acquiring input data.
4-71
public class DoubleNumber
{
public static void main(String[] args)
{
int value, doubleValue;
String input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");
value = Integer.parseInt(input);
while (!(value == 0))
{
doubleValue = value*2;
}
System.exit(0);
} 4-72
public class DoubleNumber
{
public static void main(String[] args)
{
int value, doubleValue;
String input = JOptionPane.showInputDialog("Please enter a value to double (0 to stop):");
value = Integer.parseInt(input);
4-74
import java.text.DecimalFormat;
4-77
Deciding Which Loops to Use
The while loop:
Pretest loop
Use it where you do not want the statements to execute if the
condition is false in the beginning.
The do-while loop:
Post-test loop
Use it where you want the statements to execute at least one
time.
The for loop:
Pretest loop
Use it where there is some type of counting variable that can be
evaluated.
4-78
CONTRASTING
PRE VS. POST TEST LOOPS
Although slightly more work to implement the while loop is the
most powerful type of loop.