-3

I need to have three arrays. The first array will allow the user to enter the points scored by a basketball team of 10 players for game 1. The second array will allow the user to enter the points scored for game 2. The third array will add the first two arrays together.

I'm stuck on the first part. I don't understand how to get the user to enter a number. I tried an input, but I got an error. How do I make it so the user can enter a number?

import java.util.Scanner;

public class array2 {

    public static void main(String[] args) {

        int i;
        int [] game1 = new int[10];

        // Enter Points scored by players in game 1
        // Enter points scored by players in game 2
        // Add arrays together

        Scanner scanLine = new Scanner(System.in);
        Scanner scanInt = new Scanner(System.in);

        for (i=0;i<game1.length;i++)
            {
                System.out.println ("The score of game 1 is " + game1[i]);
            }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • What error do you get exactly? Please read the [mcve] page. – user202729 Apr 02 '18 at 15:12
  • [Possible duplicate](https://stackoverflow.com/questions/4232588/how-to-use-multiple-scanner-objects-on-system-in). Besides your code doesn't really "scan" anything. – user202729 Apr 02 '18 at 15:13
  • Possible duplicate of [using scanner to input data into an array](https://stackoverflow.com/questions/32566862/using-scanner-to-input-data-into-an-array) – Raman Shrivastava Apr 02 '18 at 15:16

3 Answers3

1

You can get points scored by a basketball team of 10 players for game1 array in following way...

Scanner scanner = new Scanner(System.in);

int[] game1 = new int[10];
for (int i = 0; i < 10; i++) {
     game1[i] = scanner.nextInt();
}
scanner.close();

After doing this, you can print the array so that you can verify that you have got correct input from the user while you are developing the feature...

for (int i = 0; i < 10; i++) {
    System.out.println(game1[i]);
}

And after that, you can get points scored by a team of 10 players for game-2 and game-3 in game2 and game3 arrays respectively...

Harsh Mehta
  • 571
  • 3
  • 16
0

If points scored is integer type, try use nextInt() to read one integer:

Scanner scanner = new Scanner(System.in)
int number = scanner.nextInt();

Then you can save your input in array:

game1[0] = number;

For fill array you can use for loop:

for(i=0; i < game1.length; i++){
    game1[i] = scanner.nextInt();
}
0

Firstly, you only need one Scanner - you can use it as many times as you like.

At the point in your code where you need to read something, set a variable equal to

scanLine.nextLine()
Or
scanLine.nextInt()

You'll probably want to do some input validation on what you've scanner to make sure it is what you're expecting

The Java API documents for Scanner should be quite helpful for understanding how to use a scanner.

Sean
  • 212
  • 1
  • 10