Handout 2. Input and Output using JOptionPane methods. Boolean Operators. Java Control Structures: Conditional Statements. Formatting decimal output

Handout 2 CS603 – Object-Oriented Programming–Fall’16 Page 1 of 9 Handout 2 Input and Output using JOptionPane methods. Boolean Operators. Java Con...
Author: Milo Nash
3 downloads 1 Views 148KB Size
Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 1 of 9

Handout 2 Input and Output using JOptionPane methods. Boolean Operators. Java Control Structures: Conditional Statements. Formatting decimal output. JOptionPane methods. In addition to the Scanner class, an also use the Swing input/output dialogs from the javax.swing package, JOptionPane. •

Package: directory containing classes that can be imported into a program. ♦ ♦

The java.lang package is imported automatically into Java programs.  Contains the System class: System.out.println Other packages must be explicitly imported using the import statement.

To import a particular class: import javax.swing.JOptionPane; // imports 1 class

To import all classes from a package: import javax.swing.*; //imports all classes in the swing //directory

showInputDialog: • method in the JOptionPane class • Displays a popup window for accepting user input • User Input is returned as a String • Must precede name of method with its class name JOptionPane.showInputDialog(“put prompt for input here”);



Window becomes invisible after user clicks “ok” button. Must be terminated:



System.exit(0);// ends program and releases resources

o The 0 indicates normal termination Example: import javax.swing.*; // or, import javax.swing.JOptionPane; //Get user input and print it out public class SimpleIO { public static void main(String [] args) { String strIn = JOptionPane.showInputDialog("Enter a string"); System.out.println("The user entered: " + strIn); System.exit(0); //must include!! } }

1

Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 2 of 9

Output alternative to printing to console: showMessageDialog •

method in the JOptionPane class • Displays a popup window for displaying messages, such as output •

Precede name of method with its class name if using it within a different class



JOptionPane.showMessageDialog(null,“put output here”); 



The null value tells Java to create a default window for showing the dialog.

Also requires System.exit(0); for proper termination.

Example: import javax.swing.*; // or, import javax.swing.JOptionPane; //Get user input and print it out public class SimpleIO { public static void main(String [] args) { String strIn = JOptionPane.showInputDialog("Enter a string"); JOptionPane.showMessageDialog(null,"User entered: " + strIn); System.exit(0); } }

Converting Input • showInputDialog returns user input as a String • Can convert String to numeric data type: String s = “3”; int x; double y; x = Integer.parseInt(s); //convert s to int and store to x y = Double.parseDouble(s); //convert s to double and store to y

Examples: import javax.swing.*; public class IoTest { public static void main(String [] args) { // prompt for user input // data of type String is returned String storeInput = JOptionPane.showInputDialog("Enter a” + “ number from 1 to 100 "); //convert input from String to int int stuGrade = Integer.parseInt(storeInput); System.out.println("The user entered: " + stuGrade); System.exit(0); //release resources }}

2

Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 3 of 9

Note: if user does not enter an integer, even though the prompt calls for a whole number, a runtime error will occur while executing Integer.parseInt(storeInput). Can prompt for input and convert to correct data type in 1 line: import javax.swing.*; public class IoTest { public static void main(String [] args) { // prompt for input // convert from String to double // and store to a variable of type double double ave = Double.parseDouble (JOptionPane.showInputDialog ("Enter the class average")); System.out.println("Class average = " + ave); System.exit(0); } }

CONTROL STRUCTURES Selection: if statement if (condition) Statement if (condition) Statement

if (condition){ Statement-block }

Examples: if(temperature = 60) pf = "passed"; // grade at least 60 else pf = "failed"; // grade below 60 // print result System.out.println( "The student " + pf); System.exit(0); // release resources and exit } }

Problem: Print the smallest of three integer inputs using only if and if-else statements.

4

Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 5 of 9

Nested if statement if (condition) if (condition) Statement // it is a good idea to use “{}s” for clarity // and is often required. Also remember to indent!! if (grade >= 80) { if (grade < 90) System.out.println(“B”); else System.out.println(“A”); } Multibranch selection using nested if-else statements if (condition1) Statement1 else if (condition2){ Statement2Block } else if (condition3) Statement3 ... else // or, if need final condition: else if (conditionn) Statementn Note: if more than one statement, create a statement block, as shown for condition 2 above.

Problem: Fix the next problem to make it work correctly: /* Note that the {}s are required in this example */ if (grade >= 60) { if (grade >= 90) System.out.println("A"); if (grade >= 80) System.out.println("B"); if (grade >= 70) System.out.println("C"); else System.out.println("D"); } else System.out.println("F");

5

Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 6 of 9

Boolean (logical) Operators: join expressions that evaluate to boolean values Includes:

&& (AND)

|| (OR)

! (NOT)

&&: both conditions must be true for statement to be true ||: at least one of the two conditions must be true for the statement to be true !: reverses the value of a boolean condition

Examples: int quizGrade = 85; int finalGrade = 92; boolean a = (quizGrade >= 80 && quizGrade < 90); System.out.println(“student earned a B is ” + a); if (quizGrade > 90 || finalGrade > 90) System.out.println(“student earned an A is true"); a =!(finalGrade < 60); System.out.println("student passed is " + a);

Problem: Assume variable yearHired stores the year an employee was hired. Write a code segment that prints “found” if the yearHired is in 1990’s but is not one of 1992 or 1993.

6

Handout 2

CS603 – Object-Oriented Programming–Fall’16

Page 7 of 9

switch statement: implements multibranch selection

takes the place of the if-else-if-else statement. Switch statement: syntax switch(test-expression) { case Case_Label_1: statements … break; case Case_Label_2: statements … break; … default: statements … break; } •



Test-expression must have type char, int, short or byte; Java 7 allows String! test-expression and Case_Label must have the same type

Example: int value = Integer.parseInt(JOptionPane.showInputDialog(“Enter a number”)); switch (value){ case 1: case 2: System.out.println("Buckle my shoe"); break; case 3: case 4: System.out.println("Shut the door"); break; case 5: case 6: System.out.println("Pick up sticks"); break; case 7: case 8: System.out.println("Don't be late"); break; default: System.out.println("Do it again"); }

7

Handout 2



CS603 – Object-Oriented Programming–Fall’16

Page 8 of 9

Execution of a switch statement:

Go to the case label having the same value as the test-expression or, if no match is found, go to the default label. If no match and no default, the statement ends. If a match is found, continuing executing statements in order until a break is encountered or the end of the switch statement is reached .If a break statement is not used, the flow of control will continue into the next case. Sometimes this can be appropriate, but usually we want to execute only the statements associated with one case. Practice problem: decide if the following tasks can be encoded using the switch statement, or require an if-else statement: Print a message characterizing the severity of an earthquake based on the Richter number n: Richter number (n) n