Class 1 ~ Chapter 1

advertisement
Class 13
1
Chapter Objectives
Use a while loop to repeat a series of
statements
 Get data from user through an input
dialog box
 Add error checking to user input

2
2
while (expression)
statement;
while (expression)
{
statement;
statement;
// Place as many statements here
// as necessary.
}
3
String response;
int number =0;
1. Test this expression.
while (number ! = 99)
{response = JOptionPane.showInputDialog(
“Enter a number”);
number = Integer.parseInt(response);
}
2. If the expression is true,
perform the input statement.
4
String response;
int number =-1;
1. Test this expression.
2. If the expression is true,
perform the code within the
{}
while (number < 0)
{response = JOptionPane.showInputDialog(
“Enter a number”);
number = Integer.parseInt(response);
if (number < 0)
JOptionPane.showMessageDialog(null,
“error..do not enter numbers less than zero”,
”Error Message”,JOptionPane.ERROR_MESSAGE);
}
5
Loop
int test = 0;
while (test < 10)
{
System.out.println(“Hello”);
test = test +1;
}
// infinite loop
int test = 0;
while (test < 10)
{
System.out.println(“Hello”);
}
6
Loop
// infinite loop (ended here)
int test = 0;
while (test < 10);
{
System.out.println(“Hello”);
test = test +1;
}
7
Num is compared to 10.
If it is less than 10, the code within
the { } is executed.
When the output statement executes, num is
1 greater than it was in the
relational test.
int num = 0;
while (num <10)
{ num=num +1;
System.out.println(num + “
(num*num));
}
“+
8
Program Output
1
2
3
4
5
6
7
8
9
10
1
4
9
16
25
36
49
64
81
100
9
Counter Controlled Loop
public static void main(String a[])
{ int numScores, count =0 ; String answer1;
int total =0;
double average;
JOptionPane.showMessageDialog(null,
“This program will give you the \n“ +
“average of test scores. entered”);
answer1=JOptionPane.showInputDialog(null,
“How many test scores do you have ? “);
numScores = Integer.parseInt(answer1);
10
11
12
Counter Controlled Loop
while (count <=numScores)
{ String scoreEntered;
int score;
count = count +1;
scoreEntered = JOptionPane.showinputDialog(
null, “Enter score ” + count);
score = Integer.parseInt(scoreEntered);
total = total + score;
}
average = (double) total/count;
JOptionPane.showMessageDialog(null, “The” +
“average of the test scores is “ + average);
}
13
14
15
Conclusion
of Class 13
16
Download