简体   繁体   中英

Java validation error from user input

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, eg 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

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

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 ( , )

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

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!");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM