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;
}
答案 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