Home > OS >  Program skips one value in array when I am using Java
Program skips one value in array when I am using Java

Time:11-06

How can I add the last value since array starts from zero?

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];
        for(int y=0;y<numplay ;y  )
        {
            if(y > 0)
            {
                System.out.print("Goals score by player #"  y  ": ");
                players[y]=x.nextInt();
            }
        }
    }
}

Output:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3

Desired output:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3
Goals score by player #4: 3

CodePudding user response:

Your code is not prompting for the last player because you skip the first iteration of the loop due to the if (y > 0) condition. Consider this code:

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

CodePudding user response:

Just print the value of y plus one.

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];
    for (int y = 0; y < numplay; y  ) {
        System.out.print("Goals score by player #"   (y   1)   ": ");
        players[y] = x.nextInt();
    }
}

By putting y 1 in brackets, inside call to print, Java understands that it means add operation and not string concatenation.

Running above code gives me this output:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3
Goals score by player #4: 4
  •  Tags:  
  • java
  • Related