我是编程新手。需要建议您缩短以下代码。
public class Exercise4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[][] info = {{"010","John","Male","21"},
{"011","Mary","Female","25"},
{"012","Joseph","Male","24"},
{"013","Peter","Male","22"}};
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(j == 0) {
System.out.print("ID: ");
} else if(j == 1) {
System.out.print("Name: ");
} else if(j == 2) {
System.out.print("Gender: ");
} else if(j == 3) {
System.out.print("Age: ");
}
System.out.println(info[i][j]);
}
System.out.println();
}
}
}
这将显示以下输出。有没有办法改善/缩短我的代码?我认为有一种方法可以缩短它,但我无法弄明白。
输出:
答案 0 :(得分:2)
当您使用硬编码数组边界时,您也可以按以下方式执行:
for(int i = 0; i < info.length; i++) {
System.out.printf ("%nID: %s%nName: %s%nGender: %s%nAge:%s%n",
info[i][0], info[i][1], info[i][2], info[i][3]);
}
答案 1 :(得分:0)
你可以这样做 -
List<String> headerList = Arrays.asList(new String[]{"ID","Name","Gender","Age"});
List<String[]> infoList = Arrays.asList(info);
for(String[] s: infoList){
int count = 0;
for(String header : headerList){
System.out.println(header+": "+s[count]);
count++;
}
}
注意:标题长度和行长度应相同。