我想在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);
}
}
}