显示垂直直方图java

时间:2016-12-09 23:16:03

标签: java

我需要帮助才能垂直显示我的星星。但我不知道该怎么做。我设法展示了这颗恒星,但它不整齐。如果您有任何其他方法,请显示您的答案。

这是我的变量:

    int Count = 0; //total number of marks entered 
    int catOne = 0; //counters for each catergory
    int cat2 = 0;   //counters for each catergory
    int cat3 = 0;  //counters for each catergory
    int cat4 = 0; //counters for each catergory
    int mark = 0;
    int totalPassed = 0; //entered by user
    double averageScore = 0;
    int lowMark = 102;
    int highMark = 0;
    int mark1 = 0;
    int value = 0;
    boolean run = false;

这是我的垂直星代码:

    //Vertical
    System.out.println("0-29  30-39  40-69  70-100");
    for (int i = 0; i < catOne; i++) {
        System.out.println("  ");
        System.out.print("");
        System.out.print("*        ");//display the amount of students recieved the mark


    }
     System.out.print("");
    for (int i = 0; i < cat2; i++) {
        System.out.println("  ");
        System.out.print("");
        System.out.print("        *"); //display the amount of students recieved the mark

    }
     System.out.print("");
    for (int i = 0; i < cat3; i++) {
        System.out.println("  ");
        System.out.print("");
        System.out.print("              *");//display the amount of students recieved the mark
    }

    for (int i = 0; i < cat4; i++){ 
        System.out.println("  "); 
        System.out.print("");
        System.out.print("                        *"); //display the amount of students recieved the mark
        System.out.print("");
    }

此代码的输出为:

0-29  30-39  40-69  70-100

*          
*  
*        
        *  
              *  
                        *  
                        *  
                        *

1 个答案:

答案 0 :(得分:0)

使用数组而不是循环的单独变量。这使得它变得容易得多。由于恒星的数量可能在每个类别中有所不同,因此请检查最大星数,这表示外环打印线的边界。内循环通过迭代categories数组来创建每一行。这是代码:

int[] categories = new int[4];

// ...set the values for the categories directly...
// ...or copy them like this:
// categories[0] = catOne; 
// categories[1] = cat2; 
// categories[2] = cat3;
// categories[3] = cat4;

int maximum = 0;
for (int value : categories) {
    if(value > maximum) {
        maximum = value;
    }
}

// The above loop is the short version of:
// for (int i = 0; i < categories.length; i++) {
//     if (categories[i] > maximum) {
//         maximum = categories[i];
//     }
// }

// Added "00", so the colums have equal width
System.out.println("00-29  30-39  40-69  70-100\n");

for (int i = 0; i < maximum; i++) {
    for (int j = 0; j < 4; j++) {
        if (categories[j] > i) {
            System.out.print("*      ");
        } else {
            System.out.print("       ");
        }
    }
    System.out.println();
}