0

我希望你能帮助我完成这个编码。我正在尝试创建一个条形图,但它似乎并不适合我。我正在尝试在下面进行输出,但是当我运行它时,我会[Red, Yellow, Blue](0)重复。我觉得我快要解决这个问题了。如果有人可以将我推向正确的方向,我将不胜感激。

import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //These arrays are not to be modified and should only use these 2 arrays.
        short[] points ={1,2,1,1,1,1,1,1,3,4,1,5};
        String[] teams ={"Red","Yellow","Blue","Blue","Blue","Red","Yellow","Red","Yellow","Red","Blue","Blue"};
        Set<String> uniqueTeams = new HashSet<String>(Arrays.asList(teams));
        Barchart(points, teams, uniqueTeams);
    }

    public static void Barchart(short[] points, String[] teams, Set<String> uniqueTeams){
        byte count=0;
        for(int index=0; index < points.length; index++){
            if(teams.equals(uniqueTeams)){
                count++;
            }
        }
        for(int index=0; index < points.length; index++){
            System.out.println(uniqueTeams + "("+ count + ")");
        }

    }
}

//Output should look like this:
//
//Red(7): *******
//
//Yellow(6): ******
//
//Blue(9): *********

我有一个想法如何以另一种方式做到这一点,但我不知道如何。如果有人可以在下面回答这个问题。如果没有我在团队数组中所做的双倍操作,我如何能够获取或创建一个新数组?所以数组看起来像 String[] uniqueTeams = {"Red, "Yellow", "Blue"}; 但不是初始化或声明它,而是创建一种方法让程序自行创建(如果有意义的话)。

4

1 回答 1

0

uniqueTeams直接打印出来。uniqueTeams是类型Set。你应该做的是循环浏览集合中的每个项目,并打印出它们旁边的星星。

OOP 方法

如果是我,我不会将所有内容都放在单独的数据结构中,这会导致代码非常混乱。为什么不创建一个Bar包含值和名称的对象。然后你只需要循环一个类型的集合Bar并调用toString()你将覆盖的方法。

当我在这里时

我想我不妨一步一步地向您介绍 OOP 方法。使用面向对象编程,我们希望在对象中包含相似的数据。例如,酒吧的名称和价值是一个很好的对象;所有数据都与班级有关。

class Bar
{
private int count;
private String name;
    // Some values here to store the count and the name of the bar.

public Bar(String name, int count)
{
            // Assign those values in the constructor.
    this.name = name;
    this.count = count;
}
// Override the Object toString() method, and replace it with our code:
public String toString()
{
    String stars = "";
    for(int x = 0; x < count; x++)
    {
        stars += "*";
    }
            // Create the stars string, and append it to the name and count.
    return name + ":" + count + " | " + stars;
}
}

现在访问此代码比您的解决方案简单得多。首先,我们创建一个ArrayList类似barChart存储所有值的东西,并将其参数化为 type Bar

  ArrayList<Bar> barChart = new ArrayList<Bar>();

然后我们可以在中添加一些测试用例:

  barChart.add(new Bar("Red", 10));
  barChart.add(new Bar("Blue", 20));
  barChart.add(new Bar("Green", 12));

现在,因为您已经覆盖了该toString方法,您现在可以简单地将对象传递给一个System.out.println()函数。就像是:

  for(Bar b : barChart) { 
     System.out.println(b);  
  }

输出

红色:10 | *********
蓝色:20 | ********************
绿色:12 | ************

于 2013-04-18T09:45:02.843 回答