【发布时间】: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 (“将一组键映射到值”)。每次有“[许多]重复变量”时,都应该[几乎]使用这些基本数据结构之一或类似的派生数据结构,尤其是当变量名称添加数字时:}
-
创建一个包含
name和score的类,然后用您的姓名填充列表并循环遍历它以存储分数并再次显示分数。
标签: java optimization variable-assignment