我创建了一个 Java 程序,我想显示统计信息。
当用户输入1
时,它是单一的。当用户输入2
时,它是一对。当用户输入 3
时,它是一个 3 的家庭。
示例如下:
Scanner sc = new Scanner(System.in);
System.out.print("Enter group #1: ");
int g1 = sc.nextInt();
sc.nextLine();
System.out.print("Enter group #2: ");
int g2 = sc.nextInt();
sc.nextLine();
System.out.print("Enter group #3: ");
int g3 = sc.nextInt();
sc.nextLine();
System.out.print("Enter group #4: ");
int g4 = sc.nextInt();
sc.nextLine();
int[] numbers = {g1,g2,g3,g4};
int[] count = new int[] { 0, 0, 0};
String[] category = new String[]{"Single", "Couple","Family of 3"};
//String[][] category = new String[][] {{"Single"}, {"Couple"}, {"Family of 3"}};
String a = Arrays.toString(category).replaceAll("[\\[\\]]", "");
for (int i = 0; i < numbers.length; i++) {
count[numbers[i] - 1]++;
}
System.out.println("");
System.out.println("Statistic: ");
for (int i=2; i <count.length; i++)
{
System.out.println(a + " : " + count[i]);
}
但是显示太奇怪了。可以帮忙吗?
结果:
run:
Enter group #1: 1
Enter group #2: 1
Enter group #3: 1
Enter group #4: 1
Statistic:
Single, Couple, Family of 3 : 4
Single, Couple, Family of 3 : 0
Single, Couple, Family of 3 : 0
BUILD SUCCESSFUL (total time: 4 seconds)
正确的结果应该是:
run:
Enter group #1: 1
Enter group #2: 1
Enter group #3: 1
Enter group #4: 1
Statistic:
Single : 4
Couple: 0
Family of 3 : 0
最佳答案
而不是
for (int i=2; i <count.length; i++)
{
System.out.println(a + " : " + count[i]);
}
应该是
for (int i=0; i <count.length; i++)
{
System.out.println(category[i] + " : " + count[i]);
}
并删除变量a
。
关于java - 如何在java中显示正确的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494833/