如何将条件放入循环语句

时间:2019-06-11 18:30:59

标签: java

该程序将接收用户的输入,并将显示在数组平均值以上和以下的数字返回给输出。我正在尝试在循环中添加一个条件以退出获取输入。

import java.util.Scanner;
public class analyzeScores {

    public static void count(int[] list) {
        Scanner input = new Scanner(System.in);
        for(int i = 0; i < list.length;i++) {
            if(list[i] != 0)
                list[i] = input.nextInt();

        }
    }


    public static void sorts(int[] lists, int average) {
        int high = 0;
        int low = 0;
        for(int i = 0; i < lists.length; i++) {
            if(lists[i] >= average) {
                high +=1;
            }
            else {
                low += 1;
            }
        }
        System.out.println("The number of higher then average scores    is " + high);
        System.out.println("The number of lower then average scores is " + low);
    }
    public static void main(String[] args) {
        int[] list = new int[10];
        System.out.println("Enter the scores: ");
        count(list);
        int total = 0;
        for (int i = 0; i < list.length;i++) {
            total += list[i];
        }
        total = total / list.length;
        sorts(list, total);
    }
}

我试图弄清楚如何在count(int [] list)方法中实现输入0退出循环的方法。我试图实现if(list [i]!= 0),但弄乱了整个代码

1 个答案:

答案 0 :(得分:0)

您只需要在循环中的if语句中添加else条件, 如果您其余的代码都能正常工作,这应该可以工作

import java.util.Scanner;
public class analyzeScores {
    public static void count(int[] list) {
        Scanner input = new Scanner(System.in);
        for(int i = 0; i < list.length;i++) {
            if(list[i] != 0){
                list[i] = input.nextInt();
            }else{
                break;
            }
        }
    }


    public static void sorts(int[] lists, int average) {
        int high = 0;
        int low = 0;
        for(int i = 0; i < lists.length; i++) {
            if(lists[i] >= average) {
                high +=1;
            }
            else {
                low += 1;
            }
        }
        System.out.println("The number of higher then average scores    is " + high);
        System.out.println("The number of lower then average scores is " + low);
    }
    public static void main(String[] args) {
        int[] list = new int[10];
        System.out.println("Enter the scores: ");
        count(list);
        int total = 0;
        for (int i = 0; i < list.length;i++) {
            total += list[i];
        }
        total = total / list.length;
        sorts(list, total);
    }
}