编写此应用程序的更好方法是什么?

时间:2018-02-21 20:02:24

标签: java optimization variable-assignment

我正在为我的课做作业,我试图显示如下图像:5 kids and 5 scores

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

import java.util.Scanner; 公共课BarChart {

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(" *");

    }





}

}

2 个答案:

答案 0 :(得分:1)

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

.mdf

答案 1 :(得分:0)

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