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