当我输入我的7个整数“1 2 3 4 2 6 2”时,它将打印正确的出现次数。但它会在“49 50 51 52 53 54 55”打印数字...我的代码中缺少什么或者我需要更改什么才能打印正确的数字?
public static void main(String[] args)
{
final int maxEntryCount = 7;
int [][] numbers = new int [maxEntryCount][2];
System.out.print("Enter " + maxEntryCount + " integers separated by spaces: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.next().charAt(0));
}
for (int i = 0; i < maxEntryCount; i++) {
for (int j = 0; j < maxEntryCount; j++) {
if (numbers[i][0] > 0 && numbers [j][0] == numbers[i][0]) {
numbers[i][1]++;
if (j > i) {
numbers[j][0] = 0;
}
}
}
}
for (int i = 0; i < maxEntryCount; i++) {
if (numbers[i][0] > 0) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " times");
if (numbers[i][0] == 1) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " time");
}
}
}
}
答案 0 :(得分:3)
只需更改循环,即可将user input
改为:
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.nextInt());
}
在您的代码中,您将输入作为字符读取。当您输入1
时,它将采用ASCII
值代替1
我将其更改为input.nextInt()
,用于将int作为输入。