简体   繁体   English

"如何读取 0-50 范围内的任意数量的整数并计算每个输入的出现次数"

[英]How to read an arbitrary number of ints that are in the range 0-50 and count the occurences of each entered

I'm doing this as a practice problem for arrays and I am having a hard time figuring out how to get it to actually count the input.我这样做是作为数组的练习题,我很难弄清楚如何让它实际计算输入。

The full problem reads:完整的问题如下:

"Design and implement an application that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. After all input has been processed, print all of the values (with the number of occurrences) that were entered one ore more times." “设计并实现一个应用程序,它可以读取 0 到 50(含)范围内的任意数量的整数,并计算每个输入的出现次数。处理完所有输入后,打印所有值(以及出现次数) 输入了一次或多次。”

Perhaps the chapter didn't explain much or I am just not grasping the concept but I can't think of any way to really get started on this.也许这一章没有解释太多,或者我只是没有掌握这个概念,但我想不出任何方法来真正开始这一点。 I've looked around on Google and some of the solutions that were posted still don't make sense (some don't even work when I tested to see what they did!) and was hoping I could get some pointers on what to do here.我在谷歌上环顾四周,发布的一些解决方案仍然没有意义(当我测试他们做了什么时,有些甚至不起作用!)并希望我能得到一些关于该做什么的指示这里。

My code so far:到目前为止我的代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

    int[] array = new int[51];
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter a number");

    while (input.hasNext()){    
        int x = input.nextInt();
        if (x>=0 && x<=50) // 
            array[x]++; //should make array size equal to x + 1?
    }
}

Sorry I didn't notice hasNext(), this method used with files. 抱歉,我没有注意到hasNext()这个用于文件的方法。 So you know if there're still tokens left or not. 因此,您知道是否还有令牌。 Use another thing to break the wile loop, check for something that if the user entered it, it means they done entering data. 使用另一种方法破坏循环循环,检查是否有用户输入的内容,这表示他们已经输入了数据。 for example you can use a specific number. 例如,您可以使用特定的号码。

You're on the right track. 您走在正确的轨道上。 After you finish reading from the user, run a for loop to check if the value of the array element is greater than 1, then you print it: 从用户读取完后,运行for循环以检查array元素的值是否大于1,然后进行打印:

 for(int i = 0; i < array.length; i++) {
     if(array[i] > 1)
          System.out.println("The number: " + i + " entered " + array[i] + "times");
 }

as simple as that! 就如此容易!

Thing #1: You never made a way to stop the while (input.hasNext()){ loop. 第1点:您从未想过停止while (input.hasNext()){循环的方法。 So its going to go on forever just trying to read in integers. 因此,它会一直持续下去,只是尝试读取整数。

Do to the way Scanner#hasNext() works with System.in , it will always either return true OR it will stop executing until you enter something, then it will return true again. 按照Scanner#hasNext()System.in一起使用的方式进行操作,它将始终返回true或它将停止执行直到您输入内容,然后它将再次返回true。

A way to fix this is change "input.hasNext()" to "input.hasNext Int ()" so, once they enter something that is not an integer, the loop will stop and you can do whatever output with the array. 解决此问题的一种方法是将“ input.hasNext()”更改为“ input.hasNext Int ()”,因此,一旦输入的内容不是整数,循环就会停止,您可以对数组进行任何输出。

Consider: 考虑:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        ArrayList<Integer> array = new ArrayList<Integer>();
        int count = 0;



        while(true)
        {
            System.out.println("Please enter a number (enter a non-integer to end)");
            try{
                int x = input.nextInt();
                array.add(x);
                if (x>=0 && x<=50) {
                    count++;
                }
            }
            catch (InputMismatchException ex) {
                break;
            }
        }

        System.out.println();
        System.out.format("The numbers you entered were: %s\n", array);
        System.out.format("The count of in-range numbers was: %d\n", count);
    }
}

Output: 输出:

Please enter a number (enter a non-integer to end)
1
Please enter a number (enter a non-integer to end)
2
Please enter a number (enter a non-integer to end)
3
Please enter a number (enter a non-integer to end)
-1
Please enter a number (enter a non-integer to end)
100
Please enter a number (enter a non-integer to end)
e

The numbers you entered were: [1, 2, 3, -1, 100]
The count of in-range numbers was: 3

Apart from jedwards reply, I suppose you need the individual occurance of all accepted input. 除了jedwards的回复,我想您还需要所有接受的输入的单独出现。 If that is the case try this 如果是这种情况,请尝试此

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class OccuranceCounter {

    public static void main(String[] args) {

        Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a number or -1 to quit");
        while (input.hasNext()) {
            int x = input.nextInt();
            if (x >= 0 && x <= 50){
                Integer val = counter.get(x);
                if(val == null){
                    counter.put(x, 1);
                } else {
                    counter.put(x, ++val);
                }
            } else if(x == -1){
                break;
            }
        }

        for(Integer key : counter.keySet()){
            System.out.println(key + " occured " + counter.get(key) + " times");
        }
    }

}

I know it's answered, but you're supposed to be learning array stuff, and the accepted answer is a hashmap, so I'm going to write you a more array-centric version. 我知道它已经回答了,但是您应该正在学习数组的知识,并且可以接受的答案是一个哈希表,因此我将为您编写一个以数组为中心的版本。 You were close for the record. 您已接近备案。

int[] result = new int[51];

//this should run until you enter something that's not an int. 
//I'm leaving out print statements, and the check for 0<=x<=50
while(input.hasNextInt())
{
   result[input.nextInt()]++;        
}

for(int i = 0; i<=50;i++)
{
   if(results[i]>0)
   {
      //print something like (i+": " + results[i] + "\n")
   }
}

Let me know if you need help understanding any of it. 让我知道您是否需要帮助以了解其中的任何内容。 Although you'll probably enjoy it more if you throw it in your compiler and play around with it yourself till you get what's happening. 如果您将其放入编译器中并自己尝试使用,直到了解发生了什么,您可能会更喜欢它。

public class OccuranceCounter {
    public static void main(String[] args) {
        Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a number or -1 to quit");
        while (input.hasNext()) {
            int x = input.nextInt();
            if (x >= 0 && x <= 50){
                Integer val = counter.get(x);
                if(val == null){
                    counter.put(x, 1);
                } else {
                    counter.put(x, ++val);
                }
            } else if(x == -1){
                break;
            }
        }

        for(Integer key : counter.keySet()){
            System.out.println(key + " occured " + counter.get(key) + " times");
        }
    }
}

Try this, it works very well (by JovanDaGreat). 尝试一下,效果很好(作者JovanDaGreat)。

import java.util.Scanner;导入 java.util.Scanner;

public class Chap7ProjSP2022公共类 Chap7ProjSP2022

{ {

public static void main(String[] args) 
{
    // declaring variables
    Scanner scan = new Scanner (System.in);
    int [] store = new int [51];
    int input = 0;
        
    System.out.println("Enter arbitrary number of integers that are in the range 0 to 50");
    System.out.println("Enter integer not in the range 0 to 50 to end loop and process\nEnter integer:");
    input = scan.nextInt();
    
    // storing inputed numbers
    while (input >= 0 && input <= 50)
    {
        store[input] += 1;
        System.out.println("Enter integer:");
        input = scan.nextInt();
    }
    
    System.out.println();
    // printing numbers
    for (int i = 0; i <= 50; i++)
    {
        if (store[i] > 0)
            System.out.println(i + ": " + store[i]);
    }
                
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM