Getting User Input: CSE 114: Computer Science I Stony Brook University
Getting User Input: CSE 114: Computer Science I Stony Brook University
• There are two basic ways (for now) to get input from the user
JAVA INPUT METHODS • The Scanner class
CSE 114: Computer Science I
Stony Brook University • JOptionPane and showInputDialog()
TRADE-OFFS
System.out.print(“Enter temperature: ”);
• the input stream contains more data, AND
int temp = s.nextInt(); // read the next characters as an int
• the next value that can be read is of the given type
System.out.print(“Enter your name: ”);
• This helps you to avoid bugs where you try to read data
String name = s.nextLine(); // read next line as a String
that’s in the wrong format (or not there at all!)
JOPTIONPANE
• To
actually display the dialog box, call
JOptionPane’s showInputDialog() • showInputDialog() always returns a String
method
• To
get this into a useful format (int, double, etc.), use a
• showInputDialog() takes a wrapper class to convert the String to the desired type
message as its argument
• e.g., Integer.parseInt() or Double.parseDouble()
NEXT TIME
• Switch statements
• Loops