我很难在扫描仪中使用数组和if-else语句进行多次打印



使用数组、循环和if-else语句进行多次打印时遇到问题

源代码:

import java.util.*;
public class Main{
public static void main(String[]args)
{
Scanner x = new Scanner (System.in);
System.out.print("Enter the number of players: ");
int numplay = x.nextInt();
int players[]= new int[numplay];
int y; 

for(int i=0; i < numplay; i++)
{
System.out.print("Goals score by player #"+ (i+1) +": ");
y = x.nextInt();
players[i]=y;
if (players[i]<=10) 
{
System.out.println("Okay, fine, it's Messi");
} 
else 
{
System.out.println("Not Messi");
}    
}   
}      
}

输出:

Enter the number of players: 3
Goals score by player #1: 2
Okay, fine, it's Messi
Goals score by player #2: 3
Okay, fine, it's Messi
Goals score by player #3: 4
Okay, fine, it's Messi

可能的输出应该像这个

Enter the number of players: 3
Goals score by player #1: 2
Goals score by player #2: 3
Goals score by player #3: 4
Okay, fine, it's Messi

非梅西情况:

Enter the number of players: 3
Goals score by player #1: 10
Okay, fine, it's Messi
Goals score by player #2: 13
Not Messi
Goals score by player #3: 2
Okay, fine, it's Messi

非梅西情况可能输出:

Enter the number of players: 3
Goals score by player #1: 10
Goals score by player #2: 13
Goals score by player #3: 2
Not Messi

附言:我正在练习我的阵法,但我遇到了麻烦。

您需要的是一个boolean标志,如果任何球员的进球数超过10个,就会设置该标志。

最后,如果设置了标志,它将输出Not Messi

import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner x = new Scanner (System.in);
System.out.print("Enter the number of players: ");
int numplay = x.nextInt();
int players[] = new int[numplay];
boolean exceededBy10 = false;
for(int i = 0; i < numplay; i++)
{
System.out.print("Goals score by player #" + (i + 1) + ": ");
players[i] = x.nextInt();
if (players[i] > 10)
{
exceededBy10 = true;
}    
}   
if (exceededBy10) {
System.out.println("Not Messi");
}
else {
System.out.println("Okay, fine, it's Messi");
}
}      
}

最新更新