【问题标题】:What is a better way to program this application?对此应用程序进行编程的更好方法是什么?
【发布时间】:2018-02-21 20:02:24
【问题描述】:

我正在为我的班级做作业,并尝试显示如下图所示的内容:

问题是,我是 java 新手,我不知道如何在不对每个循环进行硬编码的情况下制作像这样的嵌套循环。我的问题是......我怎样才能让这段代码更高效、更动态?

导入 java.util.Scanner; 公共类条形图 {

public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);
    int score1;
    int score2;
    int score3;
    int score4;
    int score5;
    final String PROMPT = "Enter points scored by ";

    System.out.print(PROMPT + " Art >>>");
    score1 = scn.nextInt();

    System.out.print(PROMPT + " Bob >>>");
    score2 = scn.nextInt();

    System.out.print(PROMPT + " Cal >>>");
    score3 = scn.nextInt();

    System.out.print(PROMPT + " Dan >>>");
    score4 = scn.nextInt();

    System.out.print(PROMPT + " Eli >>>");
    score5 = scn.nextInt();

    System.out.print("Art ");

    for (int y = 1; y <= score1; y++)
    {
            System.out.print(" *");

    }
    System.out.print("\n");

    System.out.print("Bob ");

    for (int y = 1; y <= score2; y++)
    {
            System.out.print(" *");

    }
    System.out.print("\n");

    System.out.print("Cal ");

    for (int y = 1; y <= score3; y++)
    {
            System.out.print(" *");

    }
    System.out.print("\n");


    System.out.print("Dan ");

    for (int y = 1; y <= score4; y++)
    {
            System.out.print(" *");

    }
    System.out.print("\n");

    System.out.print("Eli ");

    for (int y = 1; y <= score5; y++)
    {
            System.out.print(" *");

    }





}

}

【问题讨论】:

  • 是的。使用适当的 数据结构,例如 List(“可以增长的有序值序列”)、数组(“具有固定大小的有序序列”),甚至是 Map (“将一组键映射到值”)。每次有“[许多]重复变量”时,都应该[几乎]使用这些基本数据结构之一或类似的派生数据结构,尤其是当变量名称添加数字时:}
  • 创建一个包含namescore 的类,然后用您的姓名填充列表并循环遍历它以存储分数并再次显示分数。

标签: java optimization variable-assignment


【解决方案1】:

您可以将所有名称和分数存储到数组中。然后你可以使用 for 循环遍历数组:

Scanner scn = new Scanner(System.in);
int[] scores = new int[] {0,0,0,0,0};
String[] names = new String[] {"Art", "Bob", "Cal", "Dan", "Eli"};
final String PROMPT = "Enter points scored by ";

// a loop to ask for input
// you can treat these loops as saying "for each name in the names array, do this..."
for(int i = 0 ; i < names.length ; i++) {
    // in the first iteration "names[i]" will be "Art", second iteration
    // will be "Bob", and so on
    System.out.print(PROMPT + names[i] + " >>>");
    // set the corresponding score
    scores[i] = scn.nextInt();
}

// another loop to print a bar chart
for(int i = 0 ; i < names.length ; i++) {
    System.out.print(names[i] + " ");

    for (int y = 1; y <= scores[i]; y++) {
        System.out.print(" *");

    }
    System.out.print("\n");
}

【讨论】:

    【解决方案2】:

    创建一个包含地图的列表,该列表将保存用户条目,地图将包含名称(键)和点(值)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多