0

I'm working on a sort of test in Java, in which the user is given a question like this: " 4 + ? = 12". The numbers are randomised and so is the questionsmark.

I need to make an error message for when the user input isn't an int. For example if the user types in the word "eight" instead of "8" an error message will show up. How can I do this?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Mikaela
  • 19
  • 1
  • 1
  • 2
  • 3
    Have you read about [exception handling](http://docs.oracle.com/javase/tutorial/essential/exceptions/)? – PakkuDon Sep 06 '14 at 12:23
  • 2
    You could try to convert the string response to an integer and catch the exception if the conversion fails (using a try ... catch block – ErstwhileIII Sep 06 '14 at 12:23
  • We can't do anything but guess without much more data. Are you making a GUI? Are you making a command-line program? – bmargulies Sep 06 '14 at 13:43

3 Answers3

2
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();//get the next input line
    scanner.close();
    Integer value = null;
    try
    {
        value = Integer.valueOf(input); //if value cannot be parsed, a NumberFormatException will be thrown
    }
    catch (final NumberFormatException e)
    {
        System.out.println("Please enter an integer");
    }


    if(value != null)//check if value has been parsed or not
    {
        //do something with the integer

    }
ortis
  • 2,203
  • 2
  • 15
  • 18
0

Consider the following code that both ensures that an integer is provided, and prompts the user to enter the correct type of input. You could extend the class to handle other restrictions (min/max values, etc.)

TestInput Class

package com.example.input;
import java.util.Scanner;
public class TestInput {
    public static void main(String[] args) {
        int n;
        Scanner myScanner = new Scanner(System.in);

        n = Interact.getInt(myScanner,"Enter value for ?", "An integer is required");
        System.out.println("Resulting input = " + n);
    }
}

Interact Class

package com.example.input;
import java.util.Scanner;
public class Interact {

    public static int getInt(Scanner scanner, String promptMessage,
            String errorMessage) {
        int result = 0;

        System.out.println(promptMessage);
        boolean needInput = true;
        while (needInput) {
            String line = scanner.nextLine();
            try {
                result = Integer.parseInt(line);
                needInput = false;
            } catch (Exception e) {
                System.out.println(errorMessage);
            }
        }
        return result;
    }
}
ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37
0

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.

msrd0
  • 7,816
  • 9
  • 47
  • 82
  • If he use a Swing UI, he should filter any input that would not be a number. That's the exact purpose of formatted text field => http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html . – NoDataFound Sep 06 '14 at 12:58
  • @NoDataFound I think the question was how to check whether the input is a number, and not to filter it. Else you could also use a `JSpinner` or things like that – msrd0 Sep 06 '14 at 12:59
  • True. But since you spoke of GUI, I though it would be better to propose formatted field which also do the job :) – NoDataFound Sep 06 '14 at 13:02