Search code examples
javajava.util.scannerinput-buffer

input buffer while creating multiple objects using for loop in java


I want to create multiple objects using for loop in java but this code is not showing proper output, I can take all inputs properly but output is not shown by the program for the input taken for arr[i].model=sc.nextLine();. And the program is showing "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException" error. I think it's an input buffer problem. How do I solve it?

    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);


    }
    }
    }

Solution

  • Below is modified the first for loop which works fine for you requirement

            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();
        }
    

    Also, added two lines of comment shows where to add and remove scanner. And one more thing I suggest is, while your printing the details, don't hard-code the number of cars as 10, as you have already read that value in 'n', use that for looping

    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);
    
        }