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?

3
  • 3
    Have you read about exception handling? Commented Sep 6, 2014 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 Commented Sep 6, 2014 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? Commented Sep 6, 2014 at 13:43

3 Answers 3

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

    }
Sign up to request clarification or add additional context in comments.

Comments

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;
    }
}

Comments

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.

3 Comments

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 => docs.oracle.com/javase/tutorial/uiswing/components/… .
@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
True. But since you spoke of GUI, I though it would be better to propose formatted field which also do the job :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.