显示基于用户输入的数字的出现...数组,java

时间:2011-09-09 23:54:38

标签: java

我试图让用户输入他们喜欢的任意数量的数字,然后根据他们的输入使用数组来计算用户输入的每个数字。我知道我的发生计数器在哪里说我错过了我的回复声明,因为这是我困惑的事情之一,基本上我有点难过,是的这是功课,我想学习所以我不指望完整的答案,只是一些输入,谢谢

包chapter_6;

import java.util.Scanner;

/ **  *  * @author jason  * / 公共课Six_Three {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] num = createArray();

    // prompt user for numbers
    System.out.println("Enter integers between 1 and 100: ");
    int data = input.nextInt();








}   
    // create array based off user input
    public static int[] createArray() {
        int[] num = new int[data];
        return num;
    }


    // count each occurence of input numbers from user   
    public static int[] countNumbers(int[] data) {
        for (int i = 0; i < data.length; i++)
            return ?
    } 

}

2 个答案:

答案 0 :(得分:0)

使用此

Map<Integer,Integer>occur = new HashMap<Integer,Integer>();


for(int i=0; i< data.length;++i){
int num = data[i];

if(occur.containsKey(num) ){
int old_counter = occur.get(num);
map.put(num,old_counter++);
}
else
map.put(num,1);
}

答案 1 :(得分:0)

您的代码存在一些问题。首先,除了main之外,您无法在任何方法中访问变量data,因为那是创建它的地方。其次,您当前的代码只询问用户一个数字,您需要一个循环来询问多个数字。这是一些伪代码。

Create an array with 100 spots and initialize them all to 0
Ask the user how many numbers they want to enter
Create a for loop that runs until the user has entered the amount of numbers specified
    Read in a number and store it in a variable (we'll call it n). 
    Add 1 to the (n-1)th spot in the array (For example, if the number entered was 7, set myarray[6] = myarray[6] + 1 )
Create a for loop that loops from 1-100
    Print out how many of each number was found