IC211 Lecture 8 I/O: Command Line And JOptionPane
Outline Review Project 1 Specification A Review of Scope Command Line Input –Wrapper Classes (Integer, Double, etc) I/O with JOptionPane
Scope Same as C++ Variable exists only within the block where it was declared Duplicate variable names within the same class file Example: execution class from Lab 4 Example: scope worksheet
Command Line Input Core Java 2 pg 84 public static void main (String[] args) args contains arguments from the command line Ex: MakeShape –c 3.5 args[0]: -c args[1]: 3.5 Both are Strings!
Converting Strings to Numbers (Wrapper Classes) Used to convert primitive types to Objects. Wrapper classes (Core Java pg 186) –Double, Float, Integer, Long, Short, Byte, Character, Boolean Some containers only hold objects, not primitives Can also be used to convert Strings to numbers Need to convert String representation 3.5 to numeric 3.5 –Double.parseDouble(String s) –Java SE 6 APIJava SE 6 API Ex: MakeShape.javaMakeShape.java
Output> Different! Comparing Integers, Doubles, etc. for Equality Scanner in = new Scanner(System.in); System.out.println("Enter two integers: "); Integer a = new Integer(in.nextInt()); Integer b = new Integer(in.nextInt()); if (a == b) System.out.println("Same!"); else System.out.println("Different!"); Enter two integers: Output> ??? Must use.equals() method vice ==, just like we do with Strings
JOptionPane Create message or dialog boxes without overhead of full GUI application Get input from the user with an input dialog box String name = JOptionPane.showInputDialog("What's your name?"); Part of the javax.swing package
JOptionPane Getting numeric input…must still use and input dialog box String input = JOptionPane.showInputDialog("Guess a number from 0 to 100"); Convert String input to numeric using wrapper classes int number = Integer.parseInt(input);
JOptionPane Display a message with a message dialog box JOptionPane.showMessageDialog(null, "Welcome to IC211!");
JOptionPane Getting a confirmation (yes/no) with a confirmation dialog box int done = JOptionPane.showConfirmDialog(null, “Are you finished?”); Returns an int equal to one of three static constants: –JOptionPane.YES_OPTION –JOptionPane.NO_OPTION –JOptionPane.CANCEL_OPTION
JOptionPane Example (Number Game) Guess a number from 0 to 100 –Version using console input (Scanner)Version using console input (Scanner) –JOptionPane versionJOptionPane version