java - 显示结果的一维数组问题
问题描述
package u7a1_numofoccurrinsevenints;
/**
*
* @author SNC78
*/
import java.util.Scanner;
public class U7A1_NumOfOccurrInSevenInts {
public static void main(String[] args) {
//constant for number of entries
final int MAX_INPUT_LENGTH = 7;
// array to hold input
int[] inputArray = new int[MAX_INPUT_LENGTH];
Scanner input = new Scanner(System.in);
System.out.print("Enter seven numbers (separated by spaces):");
int max = Integer.MIN_VALUE;
// loop to read input, store in array and find highest value
for(int i = 0; i < MAX_INPUT_LENGTH; i++) {
// Read a single int - Scanner has no nextInt()
inputArray[i] = (input.next().charAt(0));
if(inputArray[i] > max) {
max = inputArray[i];
}
}
// Use highest value + 1 to determine size of count array.
// Use +1 because highest index in array is always 1 less than size
int[] countArray= new int[max + 1];
// Loop through input and count by mapping value in input array to
// index number in count array. Increment value in count array at that
// location.
for(int i = 0; i < MAX_INPUT_LENGTH; i++) {
countArray[ (int) inputArray[i]]++;
}
// Loop countArray to produce output of counts.
// Loop needs to run as long as < max + 1
// Could also use i <= max
for(int i = 0; i < max + 1; i++) {
// Only print out counts for numbers that occur in input.
if(countArray[i] > 0) {
System.out.println( "Number " + i + " occurs "
+ countArray[i] + " times.");
}
}
}
}
所以这就是我正在使用的 ^^。我的输出如下:运行:
Enter seven numbers (separated by spaces):22 23 22 78 78 59 1
Number 49 occurs 1 times.
Number 50 occurs 3 times.
Number 53 occurs 1 times.
Number 55 occurs 2 times.
我已经根据类似的程序构建了这个当前程序,但无法找到为什么它返回奇数而不是输入的数。就像它如何返回 49、50、53... 而不是我输入的任何数字
解决方案
问题是您正在使用:
input.next().charAt(0);
在下一个 int 中扫描。这是一个 char,将其转换为 int 值(或ascii 值- 不是您想要的),然后将其添加到 int Array
。所以当你输入 20 时,它取第一个char
,2
并将其转换为它的 ascii 值, (你在's50
中输入了三个值,所以记录了 3 次)。20
50
您想使用该nextInt()
方法读取int
's:
inputArray[i] = input.nextInt();
推荐阅读
- python - 我想在我的计算机上运行一个 python 脚本,并在按下烧瓶服务器上的按钮时运行它
- r - 在 R 中,找出一个值在“列”值中重复的次数最多
- javascript - Google Appscript For Loop 仅在调用函数时运行一次
- python - Bokeh - 模型必须由单个文档拥有,TableColumn(id='1441', ...) 已经在文档中
- spring-boot - 超过 partReader.maxInMemorySize 时究竟会发生什么?
- excel - 尝试将公式超链接到另一个工作表
- python - Python 标记组中的最大值、第 75 个百分比、第 50 个百分比和最小值
- bash - 如何通过 GitHub CLI 创建具有多个受让人的拉取请求?
- go - 如何使 v2+ 版本的 Go 模块避免导入路径前缀要求?
- r - 根据多个条件将数据帧子集为多个