Reputation: 59
I'm just starting out with Java and programming in general. Could someone please explain to me why the second dialog box won't show up after I've entered the information for the first one?
Thanks!
// Java Practice
import javax.swing.JOptionPane;
import java.util.Scanner;
public class DialogTest
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String firstname;
String lastname;
int age;
JOptionPane.showInputDialog("What is " +
"your first name?");
firstname = keyboard.nextLine();
JOptionPane.showInputDialog("What is " +
"your last name?");
lastname = keyboard.nextLine();
JOptionPane.showInputDialog("How old are you?");
age = keyboard.nextInt();
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
System.exit(0);
}
}
Upvotes: 0
Views: 263
Reputation: 4707
You don't need both JOptionPane
and Scanner
. You only need one (I highly recommend Scanner
over the other).
What's happening is this: The call to JOptionPane
is opening a dialog for your user to enter a value. That value is returned by this method call, which you do nothing with. Then after the dialog is finished, you call keyboard.nextLine()
which blocks the program until the user enters another value into the command line window (or your IDE if you're running it through that).
If you want to see both options available to you, try commenting out the keyboard
lines and setting firstname = JOptionPane...
and so on. Once you've tried out that program, do the opposite: comment out the JOptionPane
calls and replace them with System.out.println
calls.
As someone who began learning input handling via JOptionPane
, I believe Scanner
is a much better utility.
Upvotes: 0
Reputation: 1106
JOptionPane.showInputDialog()
returns a String
that contains the value entered by the user. Instead of using the Scanner
class, store the return value of the method call into your variables:
String firstname, lastname, age;
firstname = JOptionPane.showInputDialog("What is " +
"your first name?");
lastname = JOptionPane.showInputDialog("What is " +
"your last name?");
age = JOptionPane.showInputDialog("How old are you?");
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
Upvotes: 2