简体   繁体   English

Java:多维数组

[英]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.我正在做多维数组,它将根据用户的输入打印至少 2 个姓名和相应年龄和薪水的数组。 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();
        }
    }
}

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.内部循环没有意义,因为您将姓名、年龄和薪水存储在第一列 ( employeeList[i][0] ) 中,这意味着薪水将覆盖输入的其余部分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM