开发者

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.

public class Six_Three {


public static void main(String[] args) {

    Scanner input = new Scanner (System.in);
    System.out.print("enter integers between 1 and 100: ");
    int[] num = new int[100];
    int data = input.nextInt();

开发者_如何学编程    while ((data = input.nextInt()) != 0) {
        num[data]++;
    }

    for (int i = 1; i < 100; ++i) { 
        if (num[i] > 0) 
            System.out.println(i + " occurs " + num[i] + " times ");
    }
}


You need two separate loops: the first to gather the information, and the second to print the results:

int data = 0;

while ((data = input.nextInt()) != 0)
{
    num[data]++;
}

for (int i = 0; i < 100; ++i)
{
    if (num[i] != 0) { /* print num[i] */ }
}


Just loop over the num array after your while loop to print the counts.

for (int index = 0; index < num.length; index++) {

    if (num[index] != 0)
        System.out.println(data + " occurs " + num[data] + " time(s).");
}


You are printing an output every time an integer is read. Your program is behaving as expected.

To get what you want, you need to scan all the input before you produce any output.

Try this instead:

        while (data != 0){
            data = input.nextInt();
            num[data]++;
        }

        for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
            if (num[i] > 0) 
                System.out.println(i + " occurs " + num[i] + " times ");
        }


The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.

while (input.hasNextInt()){
    num[input.nextInt()]++;
}


it's so simple

    int data = 0;

    int[] num = new int[100];

    int i = 0;
    while (i < num.length) {
        if ((data = input.nextInt()) == 0)
            break;

        num[i] = data;
        i++;
    }

    for (i = 0; i < 100; ++i) {
        int times = 0;
        if (num[i] != 0) {
            for (int j = 0; j < 100; j++) {
                if (num[j] == 0) {
                    break;
                } else if (num[i] == num[j]) {
                    times++;
                }
            }
            System.out.println(num[i] + " occurs " + times + " times ");
        } else {
            break;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜