First of all, you need to get the String the user typed for the '?' in the question. If you do it simply with System.in
and System.out
, you would do it like this:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();
If you thought of an easy version with GUI, you could use JOptionPane
like this:
String line = JOptionPane.showInputDialog("4 + ? = 12");
Else, if you have a real GUI, you could read the user's input from a JTextField
or similar:
String line = textField.getText();
(In this case you could also use a JFormattedTextField
that filters the input for an Integer. This will make the check whether the input is an Integer or not unnecessary.)
Now, you need to parse the String to an int
:
int value;
try
{
value = Integer.parseInt(line);
}
catch (NumberFormatException nfe)
{
// the user didn't enter an Integer
}
doSomethingWith(value);
The content of the catch
-block differs from the variant you took above. If you took the first one with System.in
and System.out
, you could write something like this:
System.out.println("Your input is not an Integer! Please try again");
If you took the version with JOptionPane
, you could write something like this:
JOptionPane.showMessageDialog(null, "Your input is not an Integer! Please try again");
Else, you need to have a JLabel
for that witch has initially no content. Now, set it for 3 seconds to the text:
errorLabel.setText("Your input is not an Integer! Please try again");
new Thread(() ->
{
try { Thread.sleep(3000); } // sleep 3 sec
catch (InterruptedException ie) {} // unable to sleep 3 sec
errorLabel.setText("");
}).start();
Note that the last version is also compatible with the second one.
Now, you should either generate a new question, or repeat the read/parse procedure until the user entered an Integer.