Language Components - WordPress.com · 11/3/2014 · Language Components ... // ComputeArea.java:...
Transcript of Language Components - WordPress.com · 11/3/2014 · Language Components ... // ComputeArea.java:...
Language Components
Reading Input from the Console
Assignment Statements and Assignment Expressions
Named Constants`
Numeric Data Types and Operations
Augmented Assignment Operators
Increment and Decrement Operators
Numeric Type Conversions
Character Data Type and Operations
The String Type
Getting Input from Input Dialogs
Evaluating Expressions and Operator Precedence
Assignment Statements and Assignment Expressions
The syntax for assignment statements is as follows:
variable = expression;
int y = 1; // Assign 1 to variable y double radius = 1.0; // Assign 1.0 to variable radius int x = 5 * (3 / 2); // Assign the value of the expression to x x = y + 1; // Assign the addition of y and 1 to x i = j = k = 1;
Examples:
An assignment statement designates a value for a variable.
An assignment statement can be used as an expression in Java.
the equal sign (=) is used as the assignment operator.
Language Components
Named Constants
The syntax for assignment statements is as follows:
final datatype CONSTANTNAME = value;
// ComputeArea.java: Compute the area of a circle public class ComputeArea { public static void main(String[] args) { final double PI = 3.14159; // Declare a constant double radius = 20; // Assign a radius double area = radius * radius * ; // Compute area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area);
Example:
A named constant is an identifier that represents a permanent value.
Language Components
Numeric Data Types
Name Range Size
byte - to 27-1 (-128 to 127) 8-bit signed
short -215 to 215-1 (32768 to 32767) 16-bit signed
int -231 to 231-1 32-bit signed
long -263 to 263-1 64-bit signed
float Negative range: -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38
32-bit
double Negative range:-1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308
64-bit
The compiler allocates memory space for each variable or constant according to its data type.
Java provides six primitive data types for numeric values, the table lists the six numeric data types, their ranges, and their storage sizes.
Language Components
Numeric Operators
When both operands of a division are integers, the result of the division is an integer and the fractional part is truncated
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Modulus (remainder) 20 % 3 2
Language Components
Exponent Operations
The Math.pow(a, b) method can be used to compute ab
System.out.println(Math.pow(2, 3)); // Displays 8.0 System.out.println(Math.pow(4, 0.5)); // Displays 2.0 System.out.println(Math.pow(2.5, 2)); // Displays 6.25 System.out.println(Math.pow(2.5, -2)); // Displays 0.16
Examples:
Language Components
Augmented Assignment Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i = i + 8
-= Subtraction assignment i -= 8 i = i – 8
*= Multiplication assignment i *= 8 i = i * 8
/= Division assignment i /= 8 i = i / 8
%= Modulus assignment i %= 8 i = i % 8
No space
Language Components
Increment and Decrement Operators
Operator Name Description Example (assume i=1)
++var preincrement Increment var by 1, and use the new var value in the statement
int j = ++i; // j is 2, i is 2 Equivalent to : i=i+1; J=i;
Var++ postincrement Increment var by 1, but use the original var value in the statement
int j = i++; // j is 1, i is 2 Equivalent to :
J=i; i=i+1;
--var predecrement Decrement var by 1, and use the new var value in the statement
int j = ——i; // j is 0, i is 0 Equivalent to :
i=i-1; J=i;
Var-- postdecrement Decrement var by 1, and use the original var value in the statement
int j = i——; // j is 1, i is 0 Equivalent to :
J=i; i=i-1;
Language Components
Increment and Decrement Operators
The increment (++) and decrement (– –) operators are for incrementing and decrementing a variable by 1
postfix increment and postfix decrement
int i = 3, j = 3; i++; // i becomes 4 J--; // j becomes 2
prefix increment and prefix decrement
int i = 3, j = 3; ++i; // i becomes 4 --j; // j becomes 2
Language Components
Increment and Decrement Operators
The differences between postfix and prefix
int i = 10; int newNum = 10 * i++;
int newNum = 10 * i; i = i + 1;
same effect as
int i = 10; int newNum = 10 * (++i)
i = i + 1; int newNum = 10 * i;
same effect as
double x = 1.0; double y = 5.0; double z = x– – + (++y); Result of running : y = 6.0, z = 7.0, x = 0.0.
Example:
Language Components
Homework:
Assume that int a = 1 and double d = 1.0, and that each expression is independent. What are the results of the following expressions? a = 46 / 9; a = 46 % 9 + 4 * 4 - 2; a = 45 + 43 % 5 * (23 * 3 % 2); a %= 3 / a + 3; d = 4 + d * d + 4; d += 1.5 * 3 + (++a); d -= 1.5 * 3 + a++;
Language Components
Character Data Type and Operations
A character data type (char) represents a single character
Example: char letter = 'A'; char numChar = '4';
The difference between : Char letter = 'A' and Char letter = “A”
A character data type (char) occupy 2 bytes of storage
Language Components
Unicode and ASCII code
import javax.swing.JOptionPane; public class DisplayUnicode { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "\u6B22\u8FCE \u03b1 \u03b2 \u03b3", "\u0645\u0631\u062D\u0628\u0627 Welcome", JOptionPane.INFORMATION_MESSAGE); } }
Java supports Unicode (16-bit character encoding)
A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal digits from \u0000 to \uFFFF
Unicode characters can be stored in a char type variable.
RUN
char letter = 'A'; char letter = '\u0041'; // Character A's Unicode is 0041
Example:
Language Components
Casting between char and Numeric Types
RUN
char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is // assigned to ch System.out.println(ch); // ch is character A
RUN
char ch = (char)65.25; // Decimal 65 is assigned to ch System.out.println(ch); // ch is character A
int i = (int)'A'; // The Unicode of character A is assigned to i System.out.println(i); // i is 65
int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System.out.println("i is " + i); // i is 101
int j = 2 + 'a'; // (int)'a' is 97 System.out.println("j is " + j); // j is 99 System.out.println(j + " is the Unicode for character " + (char)j); // j is the Unicode for character c System.out.println("Chapter " + '2'); // Chapter 2
Language Components
A string is a sequence of characters
The String Type
The char type represents only one character
Data type called String used to represent a string of characters
Examples:
String message = "Welcome to Java";
// operator + used to concatenate two strings String message = "Welcome " + "to " + "Java"; message += " and Java is fun";`
String s = "Chapter" + 2; // s becomes Chapter2
If i = 1 and j = 2, what is the output of the following statement? System.out.println("i + j is " + i + j); // i + j is 12 System.out.println("i + j is " + ( i + j)); // i + j is 3
Language Components
To read a string from the console :
The String Type
Scanner input = new Scanner(System.in); System.out.println("Enter three words separated by spaces: "); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); System.out.println("s1 is " + s1); System.out.println("s2 is " + s2); System.out.println("s3 is " + s3); RUN
To read line of string from the console :
Scanner input = new Scanner(System.in); System.out.println("Enter a line: "); String s = input.nextLine(); System.out.println("The line entered is " + s);
RUN
The next() method reads a string that ends with a whitespace character
The nextLine() method reads a string that ends with the Enter key pressed
Language Components
An input dialog box prompts the user to enter an input graphically
Getting Input from Input Dialogs
showInputDialog method is used
RUN
Language Components
We have to convert a string into a number to use it as a number
Converting Strings to Numbers
To convert a string into an int value, use the Integer.parseInt method:
To convert a string into a double value, use the Double.parseDouble method:
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
The Integer and Double classes are both included in the java.lang package, and thus they are automatically imported.
Language Components
Example: Write a program that compute the value of the payment for a load. The algorithm as follows: 1- accepts : - The annual interest rate. - Number of years. - Loan amount . 2- then: - Displays the monthly payment and total payment . 3- Using the following calculations:
loanAmount * monthlyInterestRate monthlyPayment =
1 - (1 + monthlyInterestRate) numberOfYears *12
1
monthlyInterestRate = annualInterestRate / 1200
totalPayment = monthlyPayment * numberOfYears *12
Language Components
The program(1): public class ComputeLoan{ public static void main(String[] args) { double annualInterestRate = 8.25; // Annual interest rate double monthlyInterestRate = annualInterestRate / 1200; // Monthly interest rate int numberOfYears = 3; // Number of years double loanAmount = 25000.00; // Loan amount // Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1-1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; // Format to keep two digits after the decimal point monthlyPayment = (int)(monthlyPayment * 100) / 100.0; totalPayment = (int)(totalPayment * 100) / 100.0; // Display results System.out.println("The monthly payment is $" + monthlyPayment + "\nThe total payment is $" + totalPayment); } } RUN
Language Components
The program(2): write a program using UsingInputDialog import javax.swing.JOptionPane; public class ComputeLoanUsingInputDialog { public static void main(String[] args) { // Enter annual interest rate String annualInterestRateString = JOptionPane.showInputDialog( "Enter annual interest rate, for example, 8.25:"); // Convert string to double double annualInterestRate = Double.parseDouble(annualInterestRateString); // Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200; // Enter number of years String numberOfYearsString = JOptionPane.showInputDialog("Enter number of years as an integer, for example, 5:"); // Convert string to int int numberOfYears = Integer.parseInt(numberOfYearsString); // Enter loan amount String loanString = JOptionPane.showInputDialog("Enter loan amount, for example, 120000.95:"); // Convert string to double double loanAmount = Double.parseDouble(loanString); // Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1-1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; // Format to keep two digits after the decimal point monthlyPayment = (int)(monthlyPayment * 100) / 100.0; totalPayment = (int)(totalPayment * 100) / 100.0; // Display results String output = "The monthly payment is $" + monthlyPayment + "\nThe total payment is $" + totalPayment; JOptionPane.showMessageDialog(null, output); } }
RUN
Language Components
Homework
public class Test { public static void main(String[] args) { char x = 'a'; char y = 'c'; System.out.println(++x); System.out.println(y++); System.out.println(x - y); } }
RUN
2- Use print statements to find out the ASCII code for '1', 'A', 'B', 'a', and 'b'. Use print statements to find out the character for the decimal codes 40, 59, 79, 85, and 90. Use print statements to find out the character for the hexadecimal code 40, 5A, 71, 72, and 7A.
1- Homework: Show the output of the following program:
Language Components
3- Use print statements to find out the ASCII code for '1', 'A', 'B', 'a', and 'b'. Use print statements to find out the character for the decimal codes 40, 59, 79, 85, and 90. Use print statements to find out the character for the hexadecimal code 40, 5A, 71, 72, and 7A.
RUN
int i = '1'; int j = '1' + '2' * ('4' - '3') + 'b' / 'a'; int k = 'a'; char c = 90;
4- Evaluate the following:
running
Language Components
5- Show the output of the following statements (write a program to verify your results): System.out.println("1" + 1); System.out.println('1' + 1); System.out.println("1" + 1 + 1); System.out.println("1" + (1 + 1)); System.out.println('1' + 1 + 1);
6- Evaluate the following expressions (write a program to verify your results): 1 + "Welcome " + 1 + 1 1 + "Welcome " + (1 + 1) 1 + "Welcome " + ('\u0001' + 1) 1 + "Welcome " + 'a' + 1
7- (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: fahrenheit = (9 / 5) * celsius + 32 Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8.
8- (Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas: area = radius * radius * PI volume = area * length
9- (Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program prompts the user to enter a number in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms.
10- (Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
Language Components
12- (Geometry: area of a hexagon) Write a program that prompts the user to enter the side of a hexagon and displays its area. The formula for computing the area of a hexagon is
11- (Physics: acceleration) Average acceleration is defined as the change of velocity divided by the time taken to make the change, as shown in the following formula: Write a program that prompts the user to enter the starting velocity in meters/second, the ending velocity in meters/second, and the time span t in seconds, and displays the average acceleration.
13- (Geometry: distance of two points) Write a program that prompts the user to enter two points (x1, y1) and (x2, y2) and displays their distance between them. The formula for computing the distance is : Note that you can use Math.pow(a, 0.5) to compute
Language Components
14- (Find the character of an ASCII code) Write a program that receives an ASCII code (an integer between 0 and 127) and displays its character. For example, if the user enters 97, the program displays character a.
15- (Financial application: payroll) Write a program that reads the following information and prints a payroll statement: Employee’s name (e.g., Smith) Number of hours worked in a week (e.g., 10) Hourly pay rate (e.g., 6.75) Federal tax withholding rate (e.g., 20%) State tax withholding rate (e.g., 9%)
Language Components
Relational (Comparison) Operators
Comparison operators used to compare two values.
The result of the comparison is a Boolean value: true or false.
Example : boolean b = (1 > 2); // b = false
Language Components
if Statements (One-way )
if (boolean-expression) { statement(s); }
Boolean
Expression
true
Statement(s)
false
(radius >= 0)
true
area = radius * radius * PI;
System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
false
(A) (B)
Syntax: if (radius >= 0) {
area = radius * radius * PI;
System.out.println(" The area for the circle of radius "
+ radius + " is " + area);
}
RUN
Language Components
Note:
if i > 0 { System.out.println("i is positive"); }
Wrong
if (i > 0) { System.out.println("i is positive"); }
Correct
if (i > 0) { System.out.println("i is positive"); }
if (i > 0) System.out.println("i is positive");
Ξ The Same
if Statements (One-way )
Language Components
if Statements (Two-way ) Syntax:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Boolean
Expression
false true
Statement(s) for the false case Statement(s) for the true case
Language Components
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
if Statements (Two-way ) Example:
RUN
Language Components
if Statements (Multiple) Syntax:
if (boolean-expression) {
statement(s);
}
else if {
statement(s);
}
else if {
statement(s);
}
.
.
else {
statement(s);
}
Language Components
if Statements (Multiple)
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
Example:
RUN
if (score >= 90.0)
grade = 'A';
else
if (score >= 80.0)
grade = 'B';
else
if (score >= 70.0)
grade = 'C';
else
if (score >= 60.0)
grade = 'D';
else
grade = 'F';
=
Language Components
Note:
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
if Statements (Multiple)
The else clause matches the most recent if clause in the same block.
This program prints nothing.
int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B");
This program print s B.
Language Components
Note:
if (number % 2 == 0) even = true; else even = false;
if Statements (Multiple)
The next Statements are the same
boolean even = number % 2 == 0;
Language Components
Note:
if (radius >= 0); { area = radius*radius*PI; System.out.println("The area for the circle of radius " + radius + " is " + area); }
if Statements
RUN
Syntax Vs. Symantec Errors
Language Components
Examples
Assume age = 24, gender = 'F'
(age > 18) && (gender == 'F') is true,
because (age > 18) and (gender == 'F') are both true.
(age > 18) && (gender != 'F') is false,
because (gender != 'F') is false.
Assume age = 24, gender = 'F')
(age > 34) || (gender == 'F') is true,
because (gender == 'F') is true.
(age > 34) || (gender == 'M') is false,
because (age > 34) and (gender == 'M') are both false.
Assume age = 24, gender = ‘M'
!(age > 18) is false,
because (age > 18) is true.
!(gender != 'F') is true,
because (gender != ‘M') is false.
Language Components
Write a program that checks whether a number is divisible
by 2 and 3, whether a number is divisible by 2 or 3, and
whether a number is divisible by 2 or 3 but not both:
Example
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
Language Components
switch Statement
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
Language Components
switch Statement Flow Chart
status is 0 Compute tax for single filers break
Compute tax for married file jointly break
status is 1
Compute tax for married file separatly break
status is 2
Compute tax for head of household break
status is 3
Default actions
default
Next Statement
Language Components
switch Statement Rules
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type as the value of the switch-expression.
The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression.
Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.
Language Components
switch Statement Rules
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The keyword break is optional,
but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
The default case, which is
optional, can be used to perform actions when none of the specified cases matches the switch-expression.
The case statements are executed in sequential
order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.
Language Components
Formatting Console Output
System.out.printf method is used to display formatted output on the console
Example: double amount = 12618.98; double interestRate = 0.0013; double interest = amount * interestRate; System.out.println("Interest is " + interest);
The output displayed : Interest is 16.404674
Because insteret is currency its desirable to display only two digits after the decimal point i.e (16.40).
double amount = 12618.98; double interestRate = 0.0013; double interest = amount * interestRate; System.out.printf("Interest is %4.2f", interest);
System.out.printf is used instead of System.out.println
Language Components
Formatting Console Output
The syntax to invoke this method is System.out.printf(format, item1, item2, ..., itemk)
The most common format specifiers :
Example:
Language Components
Operator precedence rule is used to determine the order of evaluation.
Multiplication, division, and remainder operators are applied first.
Addition and subtraction operators are applied last.
If an expression contains several addition and subtraction operators, they are applied from left to right.
If an expression contains several multiplication, division, and remainder operators, they are applied from left to right.
Operator Precedence
Language Components
Example:
Start scanning from the left
Precedence rule: 1- () then
2- * and / then
3- + and -
Operator Precedence
Language Components
Evaluating Expressions
(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x + 9 * (4 / x + (9 + x) / y)
Example: the arithmetic expression
Homework:
write the following arithmetic expression?
Use the following expression for square root : Math.sqrt(a)
Use the following expression for power : Math.pow(a,b)
Hints:
Language Components
Example:
Write a program that converts a Fahrenheit degree to Celsius using the formula celsius = (5/9)( fahrenheit - 32).
import java.util.Scanner; public class FahrenheitToCelsius { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a degree in Fahrenheit: ") double fahrenheit = input.nextDouble(); double celsius = (5.0 / 9) * (fahrenheit - 32); // Convert Fahrenheit to Celsius System.out.println("Fahrenheit " + fahrenheit + " is " +celsius + " in Celsius"); } }
RUN
Evaluating Expressions
Language Components
Develop a program that displays the current time in GMT in the format HH:MM:SS, such as 13:19:8.
Example : Displaying the Current Time
The currentTimeMillis method in the System class returns the current time in milliseconds elapsed since the time 00:00:00 on January 1, 1970 GMT
System.currentTimeMillis() is used to return the current time.
1. Obtain the total milliseconds since midnight, January 1, 1970, in totalMilliseconds using System.currentTimeMillis().
2. totalSeconds = totalMilliseconds / 1000 3. current second = totalSeconds % 60. 4. totalMinutes = totalSeconds /60. 5. current minute = totalMinutes % 60. 6. totalHours = totalMinutes /60. 7. current hour =totalHours % 24.
The algorithm as follows:
Language Components
Example : Displaying the Current Time
Program list:
public class ShowCurrentTime { public static void main(String[] args) { long totalMilliseconds = System.currentTimeMillis(); // Obtain the total milliseconds since midnight, Jan 1, 1970 long totalSeconds = totalMilliseconds / 1000; // Obtain the total seconds since midnight, Jan 1, 1970 long currentSecond = totalSeconds % 60; // Compute the current second in the minute in the hour long totalMinutes = totalSeconds / 60; // Obtain the total minutes long currentMinute = totalMinutes % 60; // Compute the current minute in the hour long totalHours = totalMinutes / 60; // Obtain the total hours long currentHour = totalHours % 24; // Compute the current hour // Display results System.out.println("Current time is " + currentHour + ":“ + currentMinute + ":" + currentSecond + " GMT");
RUN
Language Components
The while Loop
System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); ... System.out.println("Welcome to Java!");
100 times
Example: display the following string (e.g., Welcome to Java!) hundred times?
int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }
we could Use a loop statement as follow:
Language Components
The while Loop A while loop executes statements repeatedly while the condition is true.
The syntax for the while loop is :
while (loop-continuation-condition) { // Loop body Statement(s); }
The while loop flowchart :
int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }
Language Components
The do-while Loop
The syntax for the do-while loop is :
The do-while loop flowchart :
A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition
do { // Loop body; Statement(s); } while (loop-continuation-condition);
Language Components
The for Loop A for loop has a concise syntax for writing loops.
The syntax for the for loop is :
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; Statement(s); }
Example:
for (i = initialValue; i < endValue; i++) { // Loop body; Statement(s); }
int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); }
Language Components
Loops User mistakes
for (int i = 0; i < 10; i++); { System.out.println("i is " + i); }
for (int i = 0; i < 10; i++) { }; { System.out.println("i is " + i); }
int i = 0; while (i < 10); { System.out.println("i is " + i); i++; }
int i = 0; while (i < 10) { }; { System.out.println("i is " + i); i++; }
Language Components
Nested Loops A loop can be nested inside another loop
public class MultiplicationTable { public static void main(String[] args) { /** Main method */ System.out.println(" Multiplication Table"); // Display the table heading // Display the number title System.out.print(" "); for (int j = 1; j <= 9; j++) System.out.print(" " + j); System.out.println("\n———————————————————————————————————————"); // Display table body for (int i = 1; i <= 9; i++) { System.out.print(i + " | "); for (int j = 1; j <= 9; j++) { // Display the product and align properly System.out.printf("%4d", i * j); } System.out.println(); } } }
Example : next a program that uses nested for loops to display a multiplication table
RUN
Language Components
Keywords break and continue The break and continue keywords provide additional controls in a loop.
Example : break a loop
break used in a loop to immediately terminate the loop.
continue ends the current iteration and program control goes to the end of the loop body
public class TestBreak { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; If (sum >= 100) break; } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } }
RUN
Language Components
Keywords break and continue Example : test continue
RUN
public class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; If (number == 10 || number == 11) continue; sum += number; } System.out.println("The sum is " + sum); } }
Language Components
Controlling a Loop with a Confirmation Dialog
Example :
RUN
import javax.swing.JOptionPane; public class SentinelValueUsingConfirmationDialog { public static void main(String[] args) { int sum = 0; // Keep reading data until the user answers No int option = JOptionPane.YES_OPTION; while (option == JOptionPane.YES_OPTION) { // Read the next data String dataString = JOptionPane.showInputDialog("Enter an integer: "); int data = Integer.parseInt(dataString); sum += data; option = JOptionPane.showConfirmDialog(null, "Continue?"); } JOptionPane.showMessageDialog(null, "The sum is " + sum); } }
Language Components