1

I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated. If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors

Java

package calculator;
import java.util.Scanner;

public class calculator {
    /**
     * @param args
     */
    public static void main(String[] args) {
        double n1, n2;
        String operation;
        Scanner scannerObject = new Scanner(System.in);

        System.out.println("Enter first number");
        n1 = scannerObject. nextDouble();


        System.out.println("Enter second number");
        n2 = scannerObject. nextDouble();

        Scanner op = new Scanner(System.in);
        System.out.println("Enter your operation");
        operation = op.next();

        switch (operation)  {
        case "+":
            System.out.println("Your answer is " + (n1 + n2));
            break;

        case "-":
            System.out.println("Your answer is " + (n1 - n2));
            break;

        case "/":
            System.out.println("Your answer is " + (n1 / n2));
            break;

        case "*":
            System.out.println("Your asnwer is " + (n1 * n2));
            break;

        default:
            System.out.println("I do not know!");}
        }
            int function(){
                Scanner input = new Scanner(System.in);   
                System.out.print("Enter an integer between 1-100: ");   
                int range;
            while(true){   
                    if(input.hasNextInt()){   
                    range = input.nextInt();
                    if(0<=range && range <= 100)
                        break;
                    else
                        continue;
                    }
                    input.nextLine();  //Comsume the garbage value
                    System.out.println("Enter an integer between 1-100:");
                }
                return range;
                }

             }

and these are the error messages I get:

Errors

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextDouble(Scanner.java:2456)
    at calculator.calculator.main(calculator.java:14)

I've tried so many different things but can't get it to work as I want it.

Can anyone be of any assistance here?

Thanks for reading

2
  • What were your inputs? Commented Nov 9, 2015 at 22:25
  • I tried inputting a letter 'p' Commented Nov 9, 2015 at 22:26

4 Answers 4

1

This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.

You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html

Taken from documention on Scanner

double nextDouble()

Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.

I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.

You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Sign up to request clarification or add additional context in comments.

Comments

0

Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)

2 Comments

the code wont run when I change it to a dot, it says comma expected and then will not run at all
not your code, your input numbers should be with a dot
0

It seems that you are not entering any integer as input.

You can solve this by handling the exception this way :

try {
    if(input.hasNextInt()){   
         range = input.nextInt();
         if(0<=range && range <= 100)
             break;
         else
             continue;
    }
    input.nextLine();
}
catch (InputMismatchException e) {
    input.nextLine();
}

1 Comment

I have just tried adding this in replace of my "while" section and It throws the error InputMismatchException cannot be resolved to a type
0

Your issue is at,

scannerObject. nextDouble();

You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.

try {
    System.out.println("Enter first number");
    n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {

     System.out.println("Invalid input");
}

Then you may want to create a loop to get the input again and agin until valid input is detected.

Edit

You'll need to,

import java.util.InputMismatchException;

Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.

boolean notValidInput = true;

while(notValidInput) {
    try {
        System.out.println("Enter first number");
        n1 = scannerObject. nextDouble();
        notValidInput = false;
    }
    catch(InputMismatchException inEx) {

        System.out.println("Invalid input. Please try again!");
    }
}

6 Comments

InputMismatchException cannot be resolved to a type.... ALSO says n1 isn't initialised
Okay, so I've edited it to your most recent but how can I initialise n1 and n2, because these are now the only two errors
perhaps set the vital value to 0? double n1 = 0
That seems to have worked, it is no longer showing any errors in the code but errors are still appearing when I run the program.
Enter first number j Invalid input Exception in thread "main" Enter second number java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextDouble(Scanner.java:2456) at calculator.calculator.main(calculator.java:36)
|

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.