简体   繁体   中英

I can not figure it out

I have the following requirements for my program:

  • Write a program that reads an arbitrary number of integers in the range 1 to 50 from the keyboard and then outputs how many of each value were read.
  • Do not output zero counts.
  • Prompt the user for inputs as shown in the sample run.
  • Let the user enter 0 to terminate input.
  • Any other value outside the range 1 to 50 should get an error message.

I have done this so far:

import java.util.Scanner;
public class Countingintegers
{

    public static void main(String[] args) {
        int[] inputArray = new int[51];
        Scanner keyboard = new Scanner(System.in);
        int[] frequency = new int[50];
        for(int i = 0; i < inputArray.length; i++)
        {
                  System.out.println("Input: ");
                  inputArray[i] = keyboard.nextInt();
                  if (inputArray[i] > 0 || inputArray[i] <= 50)
            {
                         ++frequency[inputArray[i]];
            }
                            else
            {
                            break;
            }

        }
        System.out.printf("%s%10s%n", "Number", "Frequency");
        for (int number = 1; number < frequency.length; number++)
               System.out.printf("%6d%10d%n", number, frequency[number]);

    }


}

Whether all my goals achieved?

You can also do this easily using Map . If you use a TreeMap , the inputs will be sorted. I would also suggest not placing all of your code in a main method. You should create public methods within your class and create an instance of the class to call methods upon, keeping the code in your main at a minimum and at most for the purpose of gathering input.

Here is an example, leveraging Maps for tracking the number of occurrences:

    import java.util.Scanner;
    import java.util.*;

    public class Countingintegers{
        private int min, max;
        private Map<Integer,Integer> inputs = new TreeMap<>();

        public Countingintegers(int min, int max){
            this.min = min;
            this.max = max;
        }

        public void addInt(Integer value) throws IllegalArgumentException{
             if(value < min || value > max){
                throw new IllegalArgumentException();
            }
            if(inputs.containsKey(value)){
                inputs.put(value, inputs.get(value)+1);
            }
            else{
                inputs.put(value, 1);
            }
        }

        public void printCounts(){
            System.out.printf("%s%10s%n", "Number", "Frequency:");
            System.out.println(inputs);
        }

        public static void main(String[] args) {
            int totalInputs = 50;
            int numIntsLoaded = 0;
            int input = -1;
            Scanner keyboard = new Scanner(System.in);
            Countingintegers counter = new Countingintegers(1, 50);

            while(numIntsLoaded < totalInputs && input != 0){
                System.out.println("Input a number between 1-50, or 0 to exit (" + (totalInputs-numIntsLoaded) + " to go):");
                try{
                    input = keyboard.nextInt();
                    counter.addInt(input);
                    numIntsLoaded++;
                }
                catch(Exception e){
                    System.out.println("You entered an invalid input. Please try again!");
                    keyboard.nextLine();
                }
            }
            counter.printCounts();
        }
    }

My comments in the code will help you, your code was a pretty solid try. You just really over complicated it. Try to think more simply next time. You only need one array for this,

import java.util.Scanner;

public class Countingintegers {

public static void main(String[] args) {

    //Hi my name is COMMENTS please use me
    @SuppressWarnings("resource")
    //Please name your scanner objects scanner, its not for you but for other programmers. Gives us a headache when you dont.
    Scanner scanner = new Scanner(System.in);
    //You only need one array...
    int[] frequency = new int[50];
    System.out.println("Input: ");

    //This for loop goes through 51 iterations of our array.
    for (int i = 0; i < 51; i++) {
        //Make a num variable so you do not have to keep on typing scanner.nextInt(), also I recomend you get familiar with variable scope.
        Integer num = scanner.nextInt();
        //You originally made this statement incorrectly. It needs to be between 0 and 50 right? || is for or (explicit) you better learn what explicit and implict for || (bitwise or) is too while your learning...
        if (num > 0 && num <= 50)
            //frequency[num] just represents the slot in the frequency array. A tip, an array will give you zeros if you don't assign numbers to all the slots. So frequency[10], the 11th slot in your array will be equal to zero when you create it.
            frequency[num] = frequency[num] + 1;
        //In programming your not really supposed to use breaks (I have honestly no idea why, but all the senior programmers keep telling me so...), but you are def a beginner so don't worry about it for now.
        if (num== 0)    break;

    }

    //The rest is history
    System.out.printf("%s%10s%n", "Number", "Frequency");
    for (int number = 1; number < frequency.length; number++)
        System.out.printf("%6d%10d%n", number, frequency[number]);
}

}

Try to change your code:

if (inputArray[i] > 0 || inputArray[i] <= 50)
{
    ++frequency[inputArray[i]];
}
else
{
    break;
}

with this one:

if (inputArray[i] == 0) {
    break;
}
if (inputArray[i] < 0 || inputArray[i] > 50) {
    System.out.printf("Value enterd ouy of range [1-50]!");
    throw new IllegalArgumentException("Value enterd ouy of range [1-50]!");
}
++frequency[inputArray[i]];

It will

terminate input

on 0 inputs and throw exception if the input value out of the expected range.

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