java.util.InputMismatchException正在发生

时间:2019-01-17 14:16:10

标签: java

我试图在此代码中输入值,但得到

  

java.util.InputMismatchException

我已经尝试了很多次,但仍然没有获得正确的答案。 (编译正常)

import java.util.Scanner;

class Test {
    String name;
    int rollno;

    Test(String x, int y) {
        this.name = x;
        this.rollno = y;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Test[] t = new Test[2];

        for(int i = 0; i<2 ;i++) {
            String s = sc.nextLine();
            int x = sc.nextInt();
            t[i] = new Test(s,x);
        }

        for(int j = 0 ; j<2 ; j++) {
            System.out.println(t[j].name + "----" + t[j].rollno);
        }
    }
}

示例输出:

java Test
vinod
24
kumar
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 Test.main(test4.java:22)

1 个答案:

答案 0 :(得分:0)

String s = sc.nextLine();
int x = sc.nextInt();
sc.nextLine();  //  <-- switch to the next line after input int value
t[i] = new Test(s, x);

完整代码如下:

public static void main(String... args) {
    for (Test test : readData(2))
        System.out.println(test.name + " ---- " + test.rollno);
}

private static Test[] readData(int total) {
    try (Scanner scan = new Scanner(System.in)) {
        Test[] data = new Test[total];

        for (int i = 0; i < data.length; i++, scan.nextLine())
            data[i] = new Test(scan.nextLine(), scan.nextInt());

        return data;
    }
}