I am having difficulty for multiple printing in scanner using Array and Ifelse statement JAVA

I am having trouble about multiple printing using array, loops, and if-else statement

source code:

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");
          }    
      }   

   }      
}

Output:

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

Possible output should be like this

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

Not Messi Situation:

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

Not Messi Situation Possible Output:

  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

P.S. I am practicing my array and I am having trouble with it.

>Solution :

What you need is a boolean flag which will be set if any of the players has number of goals greater than 10.

At the end, if the flag is set, it will output 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");
      }
   }      
}

Leave a Reply