我是编码新手。请对我好一点。 我负责创建一个程序来比较两个排球的得分。要赢得排球比赛,一支球队必须获得25分。但是球队也必须以2获胜。这两支球队将进行5场比赛。
程序应从用户那里接受每个团队一次比赛的得分。如果用户在任何时候输入的分数违反25分规则或“以2获胜”规则,请在屏幕上打印错误,然后让用户再次输入两个分数。
当用户输入完分数后,打印出赢得比赛的球队,即赢得比赛最多的球队。
您必须在此分配中使用数组和循环。
我的程序仅对数组中的第一组分数进行评分。 如何使它存储所有五组分数?
public static void main(String[] args) {
int team1[];
int team2[];
team1=new int[5];
team2=new int[5];
int counter1=0;
int counter2=0;
int k = 0;
for (int i=0;i<=4;i++){
Scanner scanint = new Scanner(System.in);
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
////////////////////////////////////////////
if (team1[i] < 25 & team2[i] < 25){
System.out.println("That cannot be. One team must get at least 25 points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else if (team1[i] - team2[i] < 2 || team2[i] - team1[i] < 2){
System.out.println("That can't be. One team must win by at least two points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else {
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
/////////////////////////////////////////////
if (team2[i] < team1[i]){
counter1++;}
else{ counter2++;}
}
if (counter1 > counter2) {
System.out.println("Team 1 has won the game.");}
else{
System.out.println("Team 2 has won the game.");
}
答案 0 :(得分:1)
好吧,我看到的完成游戏规则很少:
那么,我们该怎么做呢?每个规则带有一些if
语句。对于第一个规则:
if ((team1 < 0) || (team2 < 0)) {
System.err.println("A score cannot be negative!");
i--;
continue;
}
第二条规则:
if ((team1 < 25) && (team2 < 25)) {
System.err.println("At least one team has to have 25 or more points!");
i--;
continue;
}
对于第三条规则(可以使用if
将其转换为一条&&
语句,但是我使它变得更易于理解):
if ((team1 > 25) || (team2 > 25)) {
if ((team1 - team2 != 2) && (team2 - team1 != 2)) {
System.err.println("If a team has more than 25 points, the other team must be two points away from it!");
i--;
continue;
}
}
请注意,continue;
意味着转到您所在循环的下一个迭代。因此,您使用i--;
转到上一个迭代,而使用{{ 1}}。这是一个技巧,可让您重新启动所在循环的当前迭代。
此外,除非我在初始数据输入循环之外的某个地方使用了分数,否则我不会使用数组(尽管您应遵循分配规则并始终使用它们)。我会立即指出游戏的得分何时无效,并且会在continue;
和int team1Wins = 0;
等一些变量中跟踪两支球队的获胜情况。