所以我试图计算这个程序中整数出现的次数。代码仍然不起作用,但我是否在正确的轨道上?
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int[] newArray = new int[myList.size()];
int index1 = -1;
int current;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index1++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index1);
index1--;
break;
}
}
for (int num2 = 0; num2 < myList.size(); num2++)
{
current = myList.get(num2);
if(current == myList.get(num2))
{
newArray[current-myList.get(num2)]++;
}
}
for (int number=0; number < newArray.length; number++)
{
System.out.println(number + "1");
System.out.println(" : " + newArray[number]);
}
}
}
编辑: 只想添加我可以运行程序,但是当我输入一个超出范围的整数(不在0到50之间)时,我收到错误
答案 0 :(得分:1)
我刚刚写完这篇文章,感谢我在修改我的代码时的downvotes,并特别声明我正在修改代码。 Hashmaps会在这里为你做到这一点。
public static void main(String args[]) {
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("Number: ");
int current = scan.nextInt();
if (current > 0 && current < 51) {
if (numbers.containsKey(current)) {
numbers.put(current, numbers.get(current)+1);
}else{
numbers.put(current, 1);
}
} else {
if(numbers.isEmpty()){
System.out.println("Nothing inputted");
loop = false;
}else{
for(Entry<Integer,Integer> e : numbers.entrySet()){
System.out.println(e.getKey() + " was entered " + e.getValue() + " times");
}
loop = false;
}
}
}
}
答案 1 :(得分:0)
您不需要像myList这样的任何其他集合。 你可以声明数组
int[] occurrences = new int[51];
可以存储范围[0,50]中元素的出现。当您从扫描仪读取 n 作为nextInt时,如果 n 在范围内或者停止读取,则应该在readed n 位置增加此数组的元素否则就是新的价值观。
如果statemest总是如此:
current = myList.get(num2);
if(current == myList.get(num2))
代码示例:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] occurrrences = new int[51];
while (true){
int value = scanner.nextInt();
if(value>=0 && value<occurrrences.length){
occurrrences[value]++;
}else{
scanner.close();
break;
}
}
for (int i = 0; i < occurrrences.length; i++) {
if(occurrrences[i]>0){
System.out.println(i + " occured " + occurrrences[i] + " times.");
}
}
}