JAVA中的Object Array给出InputMismatchException

时间:2014-11-19 04:47:19

标签: java arrays object inputmismatchexception

附上了“异常的代码和快照”。请帮我解决InputMismatchException问题。我相信在运行时输入值时出现了问题

import java.util.Scanner;

class ObjectArray
{
    public static void main(String args[])
    {
        Scanner key=new Scanner(System.in);
        Two[] obj=new Two[3];

        for(int i=0;i<3;i++)
        {
            obj[i] = new Two();
            obj[i].name=key.nextLine();
            obj[i].grade=key.nextLine();
            obj[i].roll=key.nextInt();
        }

        for(int i=0;i<3;i++)
        {
            System.out.println(obj[i].name);
        }
    }
}

class Two
{
    int roll;
    String name,grade;
}

Exception

2 个答案:

答案 0 :(得分:1)

而不是:

obj[i].roll=key.nextInt();

使用:

obj[i].roll=Integer.parseInt(key.nextLine());

这可确保正确拾取和处理整数后的换行符。

答案 1 :(得分:1)

使用Integer.parseInt(key.nextLine());

public class ObjectArray{

    public static void main(String args[]) {
    Scanner key = new Scanner(System.in);
    Two[] obj = new Two[3];

    for (int i = 0 ; i < 3 ; i++) {
        obj[i] = new Two();
        obj[i].name = key.nextLine();
        obj[i].grade = key.nextLine();
        obj[i].roll = Integer.parseInt(key.nextLine());
    }

    for (int i = 0 ; i < 3 ; i++) {
        System.out.println("Name = " + obj[i].name + " Grade = " + obj[i].grade + " Roll = " + obj[i].roll);
    }
}

}

class Two {
    int roll;
    String name, grade;
}

<强>输出

a
a
1
b
b
2
c
c
3
Name = a Grade = a Roll = 1
Name = b Grade = b Roll = 2
Name = c Grade = c Roll = 3