当前位置: 动力学知识库 > 问答 > 编程问答 >

java.util.inputMismatchException Dont know why

问题描述:

I'm trying to write a small program to calculate certain grades, but I'm getting an inputMismatchException, but I don't know why. The problem is that I get the exception before I even had the chance to enter an integer.

Could somebody help me out.

 public static void main(String[] args)

{

Scanner input = new Scanner("System.in");

int passes = 0;

int failures = 0;

int studentCounter = 1;

int result;

while(studentCounter <= 10)

{

//Zelf aangepast = output gewijzigd

System.out.println("Geef het resultaat in (1 = geslaagd, 2 = gebuisd).");

result = input.nextInt();

if(result == 1)

{

passes = passes + 1;

}

else

{

failures = failures + 1;

}

studentCounter = studentCounter + 1;

}

//Zelf aangepast = output gewijzigd

System.out.printf("Aantal leerlingen geslaagd: %d\nAantal leerlingen gebuisd: %d\n", passes, failures);

if(passes > 8)

{

//Zelf aangepast = output gewijzigd

System.out.println("Bonus voor de leerkracht!");

}

}

}

So as you can see I can't assign any number to the variable result.

网友答案:

The inputMismatchException means that the Scanner (input) received something not of int which is expected from nextInt:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

So in short, the next token you give the scanner is not an int.

网友答案:

This happens when the user does not enter a valid integer when calling Scanner.nextInt(). To solve this you could use exceptions like so:

while(studentCounter <= 10)
{
    //Zelf aangepast = output gewijzigd
    System.out.println("Geef het resultaat in (1 = geslaagd, 2 = gebuisd).");
    try {
        result = input.nextInt();
    }
    catch(InputMismatchException i) {
        System.out.println("Please enter integers only.");
        result = 0;
    }

    if(result == 1)
    {
        passes = passes + 1;
    }
    else
    {
        failures = failures + 1;
    }

    studentCounter = studentCounter + 1;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: