简体   繁体   中英

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.

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.

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. 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(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. 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.

A way to fix this is change "input.hasNext()" to "input.hasNext ()" so, once they enter something that is an integer, the loop will stop and you can do whatever output with the array. ()”,因此,一旦输入的内容整数,循环就会停止,您可以对数组进行任何输出。

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. 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).

import java.util.Scanner;

public class 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]);
    }
                
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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