Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA中的对象数组提供InputMismatchException_Java_Arrays_Object_Inputmismatchexception - Fatal编程技术网

JAVA中的对象数组提供InputMismatchException

JAVA中的对象数组提供InputMismatchException,java,arrays,object,inputmismatchexception,Java,Arrays,Object,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++)

附加异常的代码和快照。请帮我解决输入不匹配的问题。我认为在运行时输入值时有问题

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;
}
import java.util.Scanner;
类ObjectArray
{
公共静态void main(字符串参数[])
{
扫描仪键=新扫描仪(System.in);
Two[]obj=新的Two[3];
对于(int i=0;i而不是:

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

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

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

输出

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

请提供异常日志。您可能没有按正确的顺序输入数据。看起来您需要输入一个字符串、一个字符串,然后是一个int,3次。在每个
nextLine()
nextInt()之前添加println()语句会有所帮助
调用,以便您知道下一步要输入的数据类型。的可能重复。您需要在调用
nextInt
后调用
nextLine
。否则程序会在您前面接到一个
nextXXX
调用。在您输入
R
时,程序会要求
nextInt
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