[英]Java: Multidimensional Array
我正在做多维数组,它将根据用户的输入打印至少 2 个姓名和相应年龄和薪水的数组。 但是当我运行程序时,它给了我空内容。 下面是我的代码。 您的帮助将不胜感激。
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();
}
}
}
内部循环没有意义,因为您将姓名、年龄和薪水存储在第一列 ( employeeList[i][0]
) 中,这意味着薪水将覆盖输入的其余部分。
您希望将每个输入存储在数组当前行的不同列中。
只需使用一个循环:
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.