0

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


    }
    }
    }
4

1 回答 1

1

下面修改了第一个 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);

    }
于 2021-07-17T06:25:44.917 回答