问题描述
我想在 java 中使用 for 循环创建多个对象,但是这段代码没有显示正确的输出,我可以接受所有输入 正确但程序未显示为 arr[i].model=sc.nextLine(); 获取的输入的输出。并且程序显示“线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException”错误。我认为这是一个输入缓冲区问题。我该如何解决?
import java.util.Scanner;
class Object{
String company;
String model;
int price;
int wheels;
int headlights;
int a=10;
}
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int i;
System.out.println("Enter the number of objects you want
to create:");
int n;
n=sc.nextInt();
System.out.println("Enter the input for each object ");
Object arr[] = new Object[n]; //Here Object is the
datatype of arr[] and by using this line of code I am
initializing the array arr[]
for (i=0; i<n; i++){
System.out.println("Enter the details for the new
vehicle");
arr[i] = new Object();
arr[i].company=sc.nextLine();
arr[i].model=sc.nextLine();
sc.nextLine(); //By writing this line I can take input
properly but output is not shown for the previous line of code.
arr[i].price= sc.nextInt();
arr[i].wheels=sc.nextInt();
arr[i].headlights=sc.nextInt();
}
System.out.println();
for(i=0;i<10;i++){
System.out.println(arr[i].company);
System.out.println(arr[i].model);
System.out.println(arr[i].price);
System.out.println(arr[i].wheels);
System.out.println(arr[i].headlights);
}
}
}
解决方法
下面修改了第一个 for 循环,它可以很好地满足您的要求
for (i = 0; i < n; i++) {
System.out.println("Enter the details for the new vehicle");
arr[i] = new Object();
sc.nextLine(); // Add scanner here
arr[i].company = sc.nextLine();
//sc.nextLine(); // remove scanner here
arr[i].model = sc.nextLine();
arr[i].price = sc.nextInt();
arr[i].wheels = sc.nextInt();
arr[i].headlights = sc.nextInt();
}
此外,添加了两行注释显示了添加和删除扫描仪的位置。我建议的另一件事是,在打印详细信息时,不要将汽车数量硬编码为 10,因为您已经在“n”中读取了该值,请使用它进行循环
for (i = 0; i < n; i++) {
System.out.println(arr[i].company);
System.out.println(arr[i].model);
System.out.println(arr[i].price);
System.out.println(arr[i].wheels);
System.out.println(arr[i].headlights);
}