使用while循环与数组中的值进行比较

时间:2016-05-09 02:11:35

标签: java arrays

我需要程序在循环中运行,直到输入0。我的代码将以0输入结束,但在尝试运行带有数字的程序时,它仍然会结束程序。而不是运行输入的数字。 while循环是为了保持程序运行,除非输入0。

import java.util.Scanner;
public class CountCompare {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the integers between 1 and 100 (0 to end, 0 < to exit): ");
        int[] counts = new int[100];
        // Count occurrence of numbers
        count(counts);

        while(counts[0] > 0){
            // Display results
            for (int i = 0; i < counts.length; i++) {
                if (counts[i] > 0)
                    System.out.println((i + 1) + " occurs " + counts[i] +
                            " time" + (counts[i] > 1 ? "s" : ""));
            }
            System.out.print("Enter the integers between 1 and 100 : ");

            // Count occurrence of numbers
            count(counts);
        }
        System.out.print("\nEnd of run");
    }

    /** Method count reads integers between 1 and 100 
     *   and counts the occurrences of each */
    public static void count(int[] counts){
        Scanner input = new Scanner(System.in);
        int num; // holds user input
        do {
            num = input.nextInt();
            if (num >= 1 && num <= 100) 
                counts[num - 1]++;
        } while (num != 0);
    }
}

I have posted the entire program. 

输出看起来像这样

输入介于1和100之间的整数(0表示结束,&lt; 0表示退出): 23 23 4 5 6 7 8 0 4发生1次 5次发生1次 6次发生1次 7发生1次 8次发生1次 23发生2次

输入1到100之间的整数:

3 个答案:

答案 0 :(得分:1)

您的计划仍然结束,因为:

int[] counts = new int[100];

您已在此处定义了计数限制。这意味着你的循环将运行

for (int i = 0; i < counts.length; i++)// counts.length=100;

因此,只要你的代码建议你想在用户输入0时结束用户输入。所以你可以这样做:

int x=1;
int y;
    Scanner sc= new Scanner(System.in);
    while(x!=0){
    System.out.println("Enter your values");
    y=sc.nextInt();
     if(y==0){
      x=0;
}
else{
System.out.println("You entered "+y);
}

答案 1 :(得分:0)

int count=new Scanner(System.in).nextInt();
int myarray[]=new int[count];
for(int tmp=0; tmp<count;)
    myarray[tmp]=++tmp;
while(count != 0){
    for(int inc=1; inc<=count; inc++){
        System.out.println(inc + "times occur");
    }
    System.out.println("Enter 0 to exit");
    count=new Scanner(System.in).nextInt();
}

答案 2 :(得分:0)

你应该看一下

while(count [0]&gt; 0){

并尝试弄清楚main方法中while循环的目的是什么。