有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA中的对象数组提供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) 个答案

  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
    
  2. # 2 楼答案

    而不是:

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

    使用:

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

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