Java 直方图不会显示所有星号?

问题描述 投票:0回答:1

我正在做一个项目,我从一个文件中获取图书评级,按评级对它们进行排序,然后为每个评级创建一个星号直方图。所以基本上,如果列表包含从 3.8 到 4.6 的评分,则直方图显示 3.7 到 4.7,并为被该书评分的每本书显示星号。我必须打印标签,然后打印星号,我已经尝试了所有看起来的方法,但没有任何方法可以显示所有的星星。每次我运行它时,在一个评级后只打印一个星号,所以我不确定是什么问题!我会很感激我能得到的所有帮助!

public static void histogram(ArrayList <Double> theList) {
System.out.println("Histogram of Amazon Bestseller Ratings");
System.out.println("--------------------------------------");
double num = theList.get(0) - 0.10;
StringBuilder str = new StringBuilder();
    for (double i = num; i < theList.get(theList.size() - 1) + 0.10; i += 0.10) { //iterate thru labels
    System.out.printf("%.1f ", i);
        for (int j = 0; j < theList.size(); ++j) { // iterates thru list of ratings
            if (theList.get(j) == i) {
                System.out.print("*");
                }
            }
        System.out.println();
        }
      System.out.println("--------------------------------------");
       }`
java arraylist histogram
1个回答
0
投票

根据您提供的代码,问题可能出在内部 for 循环中,您在其中遍历 theList 以检查评级是否与当前标签匹配。每次为每个标签运行此循环,因此对于与当前标签匹配的每个评级,您只会得到一个星号。要解决此问题,您可以修改循环以检查当前标签内的评分范围并打印相应数量的星号。

这是您的代码的更新版本,其中包含解释更改的注释:

public static void histogram(ArrayList<Double> theList) {
    System.out.println("Histogram of Amazon Bestseller Ratings");
    System.out.println("--------------------------------------");
    double num = theList.get(0) - 0.10;
    StringBuilder str = new StringBuilder();
    for (double i = num; i < theList.get(theList.size() - 1) + 0.10; i += 0.10) {
        System.out.printf("%.1f ", i);
        int count = 0; // keep count of ratings within the range of the current label
        for (int j = 0; j < theList.size(); ++j) {
            if (theList.get(j) >= i && theList.get(j) < i + 0.10) { // check if the rating falls within the current label range
                count++;
            }
        }
        // print asterisks based on the count of ratings within the range of the current label
        for (int k = 0; k < count; k++) {
            System.out.print("*");
        }
        System.out.println();
    }
    System.out.println("--------------------------------------");
}

在更新的代码中,我们使用名为

count
的变量来跟踪落在当前标签范围内的评级计数。然后我们使用这个计数为每个标签打印相应数量的星号。

希望这可以帮助您解决代码问题!

© www.soinside.com 2019 - 2024. All rights reserved.