使用星号的等级条形图

时间:2015-02-01 20:09:33

标签: java arrays loops if-statement

我试图制作一个程序,询问用户他们想要输入多少等级。然后,在他们输入等级之后,打印一个水平条形图,其中有多少等级使用星号落在某个范围之间(范围是0-9,10-19,20-29等等到100)。现在,我的代码接受用户输入,存储输入的等级并打印落在指定范围之间但不正确的值(即如果两个等级落在80-89之间,它将打印80-89:*然后80-89 :*低于它反对80-89:**)。最后,我无法找到一种更简单的方法来代替打印多个if语句。我感谢大家的帮助!

public void grades(){
    Scanner in = new Scanner(System.in);
    System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
    int q = in.nextInt();

    double[] grades = new double[q]; //initialized array
    double sum = 0;
    for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
        System.out.println("Enter your grades: ");
        double grade = in.nextInt();
        grades[counter] = grade; //grade values stored in array
    }
    System.out.println("Bar chart of grades: "); //title of printed list
    for (int i = 0; i < q; i++){ //loop scans grades. Iterate through the grades array with filled values
        if (grades[i] <= 9) { //if grades stored in array fall within range
            System.out.println("0-9: " + '*'); //print those grades on graph
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我希望能帮到你;

grades() {

    Scanner in = new Scanner(System.in);
    System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
    int q = in.nextInt();

    double[] grades = new double[q]; //initialized array
    double sum = 0;
    for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
        System.out.println("Enter your grades: ");
        double grade = in.nextInt();
        grades[counter] = grade; //grade values stored in array
    }

    int minInterval = 0;
    int maxInterval = 9;
    // you should loop for each interval
    while (maxInterval < 100) {
        System.out.print(minInterval + "-" + maxInterval + ":"); //print those grades on graph
        // print one asteriks for each grade falls in range
        for (int i = 0; i < q; i++){ //loop scans grades. Iterate through the grades array with filled values
            if (minInterval <= grades[i] && grades[i] <= maxInterval ) { //if grades stored in array fall within range
                System.out.print("*");
            }
        }
        System.out.println();
        minInterval += 9;
        maxInterval += 9;
    }

}