我必须设计一个从0-50接收任意输入的程序,打印出所有输入ONCE,然后打印出每个输入的出现。
我在某种程度上工作,但是,当输入是:1,2,3,3,3,6,9,0,0
打印出来:
输入:发生
Number Times
1 1
2 1
3 1
3 2
3 3
6 1
9 1
0 1
0 1
代替:
输入:发生
Number Times
0 2
1 1
2 1
3 3
6 1
9 1
这是一门初学者课程,我在网上看到的大部分解决方案似乎都采用了一种我还没有学过的映射技术。
public static void main(String [] args)
{
int[] array = new int[51];
Scanner scan = new Scanner(System.in);
System.out.println("Number \t Times");
while (scan.hasNext()){
int x = scan.nextInt();
if (x>=0 && x<=50){
array[x]++;
System.out.println(x + "\t " + array[x]);
}
}
}
}
我已经尝试了多种格式化循环的方法,但我似乎无法找到如何让它打印一次只输入一次的数字。
如果你还在寻找,这是另一个答案。我将留下哈希映射的答案,因为其他人可能会觉得有用,但我决定让你当前的代码工作。
int[] numbers = new int[51];
// Small loop to get the number input
Scanner scanner = new Scanner(System.in);
for (int i=0; i<10; i++) {
System.out.print("> ");
int x = scanner.nextInt();
if (x >= 0 && x <= 50) {
numbers[x] += 1;
}
}
// Now display the results after getting input
System.out.println("Number \t Times");
for (int i=0; i<numbers.length; i++) {
if (numbers[i] != 0) {
System.out.println(i + "\t\t" + numbers[i]);
}
}
欢迎来到SO。在不使用地图或甚至将值存储在任何地方的情况下解决此问题的最简单方法是首先对数组进行排序(您给出的示例已经排序)然后只计算相邻重复项的数量。
在伪代码中,算法应该看起来像
count = 1
value = array[0];
for each item from 1 to length
if item == value
increment count
else
print value: count
count = 1
value = item
print value: count
请注意,需要有2个输出 - 每次值更改并在列表的末尾。理想情况下,您将值和值存储在对象中以避免代码重复,但我认为在此阶段它过于先进。
希望您可以相对容易地将其转换为代码。
欢迎来到StackOverflow社区!我知道你提到你还没有学过'先进的绘图技术',但为什么现在不去了解它们呢?无论如何,你很有可能在将来再次需要它们。
我们可以通过使用称为'hashmap'的东西轻松解决这个问题。散列映射非常有用,因为它允许您在每个索引,键和值上存储两个值。这很有用,因为密钥与值有关(这意味着如果你有密钥就可以找到值),并且不能有重复的密钥。
以下是使用散列图解决问题的示例。
// Here we create our hashmap. Be adding <Integer, Integer>, we are telling the hashmap
// that the the key and value will be of type Integer (note that we can't just pass in int)
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
System.out.println("Number \t Times");
while (scan.hasNext()){
int x = scan.nextInt();
if (x>=0 && x<=50){
// Check if the number has already been added
// to the hash map
if (numbers.containsKey(x)) {
// If so, we will get the existing value
// and increase it by 1
numbers.put(x, numbers.get(x) + 1);
}
else {
// Otherwise we will add the value
// to the hash map
numbers.put(x, 1);
}
System.out.println(x + "\t " + numbers.get(x));
}
}