2

注意:只是练习题,不是分数。

这是第一年Java课程中给出的一个练习题:

设计和实现一个应用程序,它可以由用户读取任意数量的整数,这些整数在 0 到 50 的范围内(包括 0 到 50),并计算每个输入的出现次数。处理完所有输入后,打印输入一次或多次的所有值(以及出现次数)。此外,编写一个不返回任何值的方法,该方法将计算用户输入的所有数字的出现次数的平均值。

这就是我所拥有的(我已经跳过了“平均发生”部分,直到我清理它):

import java.util.Scanner;
public class Main 
{       
public static Scanner scan = new Scanner(System.in);

    public static int[] userIntegers()      // this method will build the array of integers, stopping when an out-of-range input is given
    {
            System.out.println("Enter the number of integers to be recorded:  ");
            int numInts = scan.nextInt();

            int[] userArray = new int[numInts];
            int i = 0;
            while(i < numInts)
            {
                    System.out.println("Enter an integer between 1-50 inclusive:  ");
                    int userInteger = scan.nextInt();
                    if(isValidInteger(userInteger))
                    {
                            userArray[i] = userInteger;
                            i++;
                    }
                    else if(isValidInteger(userInteger) == false)
                    {
                            System.out.println("Try again.");
                    }                       
            }
            return userArray;
    }

    public static void occurrenceOutput(int[] input)         // this method will print the occurrence data for a given array
    {   
        int[] occurrenceArray = new int[51];

            int j = 0;
            while(j < 51)  // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
            {
                    for(int eachInteger : input)
                    {
                            occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1:  occurrenceArray[j];
                    }
                    j++;
            }               

            int k = 0;
            for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
            {
                    if(eachOccurrence > 1)
                    {
                            System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
                    }
                    k++;
            }
    }

    public static boolean isValidInteger(int userInput)     // checks if a user input is between 0-50 inclusive        
    {        
        boolean validInt = (51 >= userInput && userInput >= 0)?  true:  false;
            return validInt;
    }

    public static void main(String[] args)
    {
        occurrenceOutput(userIntegers());
    }
}  

有人可以指出我更优雅的方向吗?

编辑:感谢您的帮助!这就是我现在的位置:

import java.util.Scanner;
public class simpleHist
{
    public static void main(String[] args)
{
            getUserInputAndPrint();
            getIntFreqAndPrint(intArray, numberOfInts);
    }

    private static int numberOfInts;
    private static int[] intArray;
    private static int[] intFreqArray = new int[51];

    public static void getUserInputAndPrint() 
    {
            //  The user is prompted to choose the number of integers to enter:
            Scanner input = new Scanner(System.in);
            System.out.println("Enter the number of Integers:  ");
            numberOfInts = input.nextInt();

            //  The array is filled withchInteger = integer; integers ranging from 0-50:
            intArray = new int[numberOfInts];
            int integer = 0;
            int i = 0;
            while(i < intArray.length)
            {
                    System.out.println("Enter integer value(s):  ");
                    integer = input.nextInt();
                    if(integer > 50 || integer < 0)
                    {
                            System.out.println("Invalid input.  Integer(s) must be between 0-50 (inclusive).");
                    }
                    else
                    {
                            intArray[i] = integer;
                            i++;
                    }
            }

            // Here the number of integers, as well as all the integers entered are printed:
            System.out.println("Integers: " + numberOfInts);    
            int j = 0;
            for(int eachInteger : intArray)
            {
                    System.out.println("Index[" + j + "] : " + eachInteger);
                    j++;
            }
    }

public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
    //  Frequency of each integer is assigned to its corresponding index of intFreqArray:
    for(int eachInt : intArray)
    {
        intFreqArray[eachInt]++;
    }

    //  Average frequency is calculated:
    int totalOccurrences = 0;
    for(int eachFreq : intFreqArray)
    {
        totalOccurrences += eachFreq;
    }
    double averageFrequency = totalOccurrences / numberOfInts;

    //  Integers occurring more than once are printed:
    for(int k = 0; k < intFreqArray.length; k++)
    {
        if(intFreqArray[k] > 1)
        {
            System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
        }
            }

            //  Average occurrence of integers entered is printed:
            System.out.println("The average occurrence for integers entered is " + averageFrequency);
            }
    }
4

2 回答 2

2

你实际上是在寻找一个histogram。您可以使用 a 来实现它Map<Integer,Integer>,或者由于元素的范围限制在 0-50,您可以使用具有 51 个元素 [0-50] 的数组,并histogram[i]在读取时增加i

奖励:理解这个想法,你已经理解了计数排序的基础知识

于 2012-04-07T23:09:44.823 回答
1

要计算出现次数,您可以执行以下操作:

 for(int eachInteger : input) {
      occurrenceArray[eachInteger]++;
 }

这将替换您的 while 循环。

于 2012-04-07T23:11:14.480 回答