Presentation is loading. Please wait.

Presentation is loading. Please wait.

John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:

Similar presentations


Presentation on theme: "John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:"— Presentation transcript:

1 John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:

2 Test Your Work So far, it has been easy to test our programs, since there is only one sequence the computer can follow: public class Power{ public static void main(String[] args){ int answer = 1; for(int power = 0; power <= 10; power++){ System.out.println("2 ^ " + power + " = " + answer); answer = answer * 2; }

3 Test Your Work Soon, we will start writing programs that take user input Users are human beings

4 Test Your Work Program execution becomes more complex when unpredictable human beings intervene Make sure to test thoroughly We have it easy. Testing involves saving, compiling, and running on a machine that is at our fingertips It hasn’t always been that way.

5 Do While Similar to while loop, but with test at the end, not the beginning Always executes at least once int x = 0; while ( x > 0) {} will never execute do{ } while ( x > 0); will execute at least once

6 Validation import javax.swing.JOptionPane; public class ValidationDemo{ public static void main(String[] args){ int age; do{ age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age")); } while(age 100); JOptionPane.showMessageDialog(null, "You entered " + age); } // end main() } // end class

7 Validation We have covered one way to get user input, JOptionPane.showInputDialog We will soon cover at least one additional way to get input We have noted that users are human beings and accordingly are impossible to predict Input is not always usable

8 Validation Screen input for problems before using it while and do… while loops are very handy for this Example: int age; do{ age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age")); } while(age 100); System.out.println(“You entered “ + age);

9 Validation import javax.swing.JOptionPane; public class ValidationDemo{ public static void main(String[] args){ int age; do{ age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age")); } while(age 100); JOptionPane.showMessageDialog(null, "You entered " + age); } // end main() } // end class

10 Validation We could still easily make the program above break enter “a” enter We will come back to validation soon

11 Equality with Floating Point Types Due to the imprecision of floating point types, it is unwise to test floats and doubles with == operator

12 Equality with Floating Point Types import javax.swing.JOptionPane; public class GPAWrong{ public static void main(String[] args){ double grade = 4.0; do{ JOptionPane.showMessageDialog(null, "grade = " + grade); // BAD CODE AHEAD!!!! if(grade == 4.0 || grade == 3.3 || grade == 3.0 || grade == 2.3) grade -= 0.3; else grade -= 0.4; }while(grade > 2.0); }

13 Equality with Floating Point Types Instead of using equality test, use Math.abs as follows: Math.abs(a-b) < tolerance; In the first project, we can’t test accurately whether a grade value ends in.7 The project will require a test like the following: if ((Math.abs(grade - 3.7) <.02) || (Math.abs(grade - 2.7) <.02)) grade -=.4; There will also be an else statement after this.

14 Equality with Floating Point Types import javax.swing.JOptionPane; public class GPARight{ public static void main(String[] args){ double grade = 4.0; do{ JOptionPane.showMessageDialog(null, "grade = " + grade); if ((Math.abs(grade - 3.7) <.02) || (Math.abs(grade - 2.7) <.02)) grade -=.4; else grade -= 0.3; }while(grade > 2.0); }

15 15 More On Operator Precedence What loops looked like before we had do, while, and for: Consider this program (in BASIC, although BASIC does have better loop functionality!) 10 x = 1 20 print x 30 x = x + 1 40 if x = 10 goto 60 50 goto 20 60 print "done"

16 16 Operator Associativity Binary operators are those that take two operands. Example: a - b All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) x = 1 X = 10 * b;

17 Switch Chooses one statement or block to execute from among several options, based on the value of a variable 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); }

18 18 switch Statement Flow Chart

19 19 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.

20 20 switch Statement Rules 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. 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 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.

21 21 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Suppose ch is 'a': animation

22 22 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } ch is 'a': animation

23 23 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

24 24 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

25 25 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

26 26 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Next statement; Execute next statement animation

27 27 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Suppose ch is 'a': animation

28 28 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } ch is 'a': animation

29 29 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation

30 30 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation

31 31 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Next statement; Execute next statement animation

32 Switch import javax.swing.JOptionPane; public class SwitchDemo{ public static void main(String[] args){ char ageCat = 'y'; while (ageCat != 'q'){ String input = JOptionPane.showInputDialog(null, "Welcome to John's bar. Please enter your age category: \ny for under 21, m for 21-29, o for 30 and older. Enter q to quit."); ageCat = (char) input.charAt(0); switch(ageCat){ case 'y': JOptionPane.showMessageDialog(null, "Enjoy your Shirley Temple, Junior"); break; case 'm': JOptionPane.showMessageDialog(null, "You'd better stick to beer"); break; case 'o': JOptionPane.showMessageDialog(null, "You probably need some whiskey"); break; case 'q': break; default: JOptionPane.showMessageDialog(null, "Invalid input"); } // end switch } // end while } // end main() } // end class

33 33 Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign.

34 34 Frequently-Used Specifiers Specifier OutputExample %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool"

35 Printf public class PrintfDemo{ public static void main(String[] args){ int intVar = 1; double doubleVar = 3.14159; double moonRadius = 1737000; // in meters char charVar = 'a'; String stringVar = "Hi, Mom"; boolean boolVar = true; System.out.printf("\nintVar: %d; \ndoubleVar: %f; \ndoubleVar to 4 places: %7.4f; \nmoonRadius: %e; \ncharVar: %c; \nstringVar: %s", intVar, doubleVar, doubleVar, moonRadius, charVar, stringVar); } // end main() } // end class


Download ppt "John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:"

Similar presentations


Ads by Google