Input mismatch error

断了今生、忘了曾经 提交于 2019-12-14 03:59:33

问题


So, I have this little program here and I've been getting the input mismatch error. I'll post the error message below the code. To be honest, I have 0 clue why the error appears. I've checked that all the required variables have correct type assigned. If I understand correctly, the said error happens when you try to input something that is not expected, right? ( double instead of int or whatever). I probably did some stupid mistake somewhere that I cant see for some reason, so I'd appreciate your help.

    Scanner sc = new Scanner(System.in);

    int enEur = 0;
    int dvaEur = 0;
    boolean bankrot = false;
    int placilo;


    while (sc.hasNextInt() || bankrot == false){
        placilo = sc.nextInt();
         if(placilo == 1){
             enEur += placilo;
         }
         else{
             enEur --;
             bankrot = test(enEur);
             dvaEur ++;
         }
     }

So, this is the content of my main() method. The error appears in the line: placilo = sc.nextInt(). Here's the copy of the said error:

    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at evroSop.main(evroSop.java:16)

The input that I put in is basically a line of separate integers like: 1 1 1 1 2 1... and so on. I've got different examples, all of which are lines of integers of different lengths.

Cherio, George


回答1:


The condition while (sc.hasNextInt() || bankrot == false) means that you'll continue trying to read from the scanner as long as there is more input or bankrot is still false. So, if you run out of inputs and still aren't bankrupt, you'll get an exception because you'll try reading next input even though there is no more of it.

The condition should be and, not or, probably.




回答2:


Read the line as String and split it into int[]

after hasNext() call,

String str = sc.nextLine();

and split this String into int[]

Example code:

        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
                String str = sc.nextLine();
                String strArray[] = str.split(" ");
                int intArray[] = new int[strArray.length];

               for (int i = 0; i < intArray.length ; i++) {
                   intArray[i] = Integer.parseInt(strArray[i]);
               }

               for (int j : intArray) {
                    System.out.println(j);
               }
        }

Input:

1 123 456

Output:

1

123

456



来源:https://stackoverflow.com/questions/33104575/input-mismatch-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!