Mundrei
Mundrei

Reputation: 13

Java: Multidimensional Array

I'm doing multidimensional arrays that will print an array of names of at least 2 with corresponding age and salary following the input from user. But when I run the program it is giving me null content. Below is my code. Your help would be highly appreciated.

import java.util.Scanner;

public class Employee {
    public static void main(String [] args) {

        Scanner input = new Scanner(System.in);

        String employeeList [][] = new String [2][3];

        // populating
        for (int i=0; i<employeeList.length; i++){
            System.out.println("Employee #" + (i+1));
            for (int j=0; j<employeeList[i].length; j++){
                System.out.print("Name\t:");
                employeeList [i][j] = input.nextLine();             
                System.out.print("Age\t:");
                employeeList [i][j]= input.nextLine();
                System.out.print("Salary\t:");
                employeeList [i][j]= input.nextLine();
                break;  
            }           
        }

        //System.out.println();
        //System.out.println();

        //displaying
        System.out.printf("%15s%15s%15s\n", "NAME", "AGE", "SALARY");
        for (int i=0; i<employeeList.length; i++){
            for (int j=0; j<employeeList[i].length; j++){
                System.out.printf("%15s", employeeList[i][j]);
            }
            System.out.println();
        }
    }
}

Upvotes: 1

Views: 116

Answers (1)

Eran
Eran

Reputation: 393821

The inner loop makes no sense, since you store the name, age and salary in the first column (employeeList[i][0]), which means the salary will overwrite the rest of the input.

You want to store each input in a different column of the current row of the array.

Just use a single loop :

for (int i=0; i<employeeList.length; i++){
        System.out.println("Employee #" + (i+1));
        System.out.print("Name\t:");
        employeeList [i][0] = input.nextLine();             
        System.out.print("Age\t:");
        employeeList [i][1] = input.nextLine();
        System.out.print("Salary\t:");
        employeeList [i][2] = input.nextLine();
}

Upvotes: 1

Related Questions