0

附上异常的代码和快照。请帮助我解决 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;
}

例外

4

2 回答 2

1

代替 :

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

利用:

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

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

于 2014-11-19T05:04:01.893 回答
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
于 2014-11-19T05:05:09.833 回答