问题是:编写一个程序,读取 1-100 之间的整数并计算每个整数的出现次数。假设输入以 0 结尾。如果数字出现不止一次,则在输出中使用复数“times”。这是程序的示例运行:
2出现2次
3 出现 1 次
4 出现 1 次
5 出现 2 次
6 出现 1 次
23 出现 1 次
43出现1次
我已将代码中读取的整数修复为不再是 i,而是一个单独的变量“索引”,并理解为什么我收到越界异常,但我有点笨,不明白如何修复它同时添加一个标记值 0。
import java.util.Scanner;
public class countNumberOccurrence{
public static void main(String args[]){
int[] numbers = new int[100];
inputArray(numbers);
}
public static void inputArray(int[] myList){
Scanner input = new Scanner(System.in);
System.out.print("Enter integers from 1-100 (input 0 value to end inputs): ");
int index = 0;
for(int i = 1; i < myList.length - 1; i++){
if(i > 0){
index = input.nextInt();
myList[index-1]++;
}
if(myList[index-1] > 1)
System.out.println(index + " occurs " + myList[index-1] + " times ");
else
System.out.println(index + " occurs " + myList[index-1] + " time ");
}
}
}
既然你在评论中说你不能以正确的惯用方式做到这一点:
检测输入 0
并结束应用程序的正确逻辑是:
int nextInt;
while ((nextInt = input.nextInt()) != 0)
{
// do your logic here
}
// print your output here
这是处理输入的正确方法。
如无必要,切勿使用原始数组!
始终使用适当的 java.util.collections
类并使用 for/each
或适当的 Iterator
进行迭代,您将不会出现这些一次性错误。
你要找的是Multimap
这是一个仅 JDK 的解决方案:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class Q21871053
{
public static void main(final String[] args)
{
final Random rnd = new Random();
final Map<Integer, AtomicInteger> counter = new HashMap<Integer, AtomicInteger>()
{
@Override
public AtomicInteger get(final Object key)
{
if (!super.containsKey(key)) { super.put((Integer) key, new AtomicInteger(rnd.nextInt(100))); }
return super.get(key);
}
};
final AtomicInteger nextInt = new AtomicInteger(rnd.nextInt(100));
while (nextInt.get() != 0)
{
counter.get(nextInt.get()).incrementAndGet();
if (counter.size() > 1000) { nextInt.set(0); } // limit the run to 1000 numbers
else { nextInt.set(rnd.nextInt(100)); }
}
for (final Integer i : counter.keySet())
{
final AtomicInteger integer = counter.get(i);
final String format = integer.get() > 1 ? "%d occurs %s times\n" : "%d occurs %s time\n";
System.out.format(format, i, integer);
}
}
}
这是一个示例输出:
3 occurs 43 times
98 occurs 16 times
64 occurs 35 times
36 occurs 27 times
37 occurs 19 times
7 occurs 58 times
76 occurs 48 times
77 occurs 40 times
41 occurs 68 times
46 occurs 5 times
13 occurs 100 times
14 occurs 15 times
51 occurs 85 times
17 occurs 40 times
85 occurs 16 times
18 occurs 97 times
25 occurs 10 times
24 occurs 12 times
29 occurs 14 times
91 occurs 2 times
@Override
public void functionToBeRateLimited(@Nonnull final String caller)
{
// do some stuff every time here
super.timesCalled.get(caller).incrementAndGet();
// do some stuff only after a certain time has elapsed since the last time it was done
if (LIMITER.get(caller).tryAcquire())
{
System.out.println(String.format("%s Called Rate Limited Logic up to 2 times a second ( 500 ms )", caller));
}
}