如何将多个二重的汇总值放入列表中

  • 本文关键字:列表 二重 java arrays
  • 更新时间 :
  • 英文 :


这里是新手。

这是代码

for (i = 0; i < 5; i++) {
System.out.println("Enter Name of the event " + (i + 1) + " that the teams are entering");
Tevent[i] = scan.next();
} // event names

for (int a = 0; a < 1; a++) {
System.out.println("Enter rank of the team on the event"); // event ranks
teamRank[i] = scan.nextInt();
if (teamRank[i] > 3) {
System.out.println("This team will not be awarded points");
}
if (teamRank[i] == 3) {
System.out.println("5 points is granted for this event");
teamScore[i] = teamScore[i] + 5;
}
if (teamRank[i] == 2) {
System.out.println("10 points is granted for this event");
teamScore[i] = teamScore[i] + 10;
}
if (teamRank[i] == 1) {
System.out.println("20 points is granted for this event");
teamScore[i] = teamScore[i] + 20;
}

代码应该询问事件名称,然后询问级别。

根据排名,它应该在每个项目上为团队加分,然后打印出汇总值。

示例:

  • 如果我输入排名1 5次,而不是显示100,则显示20

我尝试使用多个循环,但没有成功。

我觉得我在代码上完全错了。也许还有其他方法可以做到这一点?有人能给我指路吗?谢谢

一个带有修复程序的实现:

  • 使用常数值来定义数组的大小和排名尝试的次数
  • 用计算rankswitch语句替换if中的重复代码
  • 固定数据输入以处理著名的Scanner问题
final int teamSize = 2;
String[] Tevent = new String[teamSize];
int[] teamScore = new int[teamSize];
int[] teamRank  = new int[teamSize];
final int rankCount = 3;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < Tevent.length; i++) {
System.out.println("Enter Name of the event " + (i + 1) + " that the teams are entering");
Tevent[i] = scan.nextLine();

for (int a = 0; a < rankCount; a++) {
System.out.println("Enter rank of the team on the event");
teamRank[i] = scan.nextInt();
int rank = 0;
switch (teamRank[i]) {
case 3: rank =  5; break;
case 2: rank = 10; break;
case 1: rank = 20; break;
}
if (rank == 0) {
System.out.println("This team will not be awarded points");
} else {
teamScore[i] += rank;
System.out.println(rank + " points is granted for this event");
}
}
if (scan.hasNextLine()) {
scan.nextLine();
}
System.out.println("----");
}
System.out.println("Team ranks:  " + Arrays.toString(teamRank));
System.out.println("Team scores: " + Arrays.toString(teamScore));

示例运行:

Enter Name of the event 1 that the teams are entering
event1
Enter rank of the team on the event
2 10 points is granted for this event
Enter rank of the team on the event
2 10 points is granted for this event
Enter rank of the team on the event
2
10 points is granted for this event
----
Enter Name of the event 2 that the teams are entering
event 2
Enter rank of the team on the event
1
20 points is granted for this event
Enter rank of the team on the event
3
5 points is granted for this event
Enter rank of the team on the event
3
5 points is granted for this event
----
Team ranks:  [2, 3]
Team scores: [30, 30]

最新更新