简体   繁体   中英

Get integer array input from user in java

I need to get a series of integers from the user. The user will not be prompted to enter the numbers. The input will be of the following form:

6

34 12 7 4 22 15

3

3 6 2

The first line signifies the number of integers in the second line. I first tried to read the second line as a String and broke it to integers in the code using StringTokenizer. Sine this happens in my program a lot, it was time consuming and I needed to read them directly. I remember in C++ it used to be fairly simple. The following code segment used to do the trick.

for(i=0;i<6;i++)
cin>>a[i];

To achieve this, I used the java.util.Scanner and my code looks as below:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Scanner src = new Scanner(System.in);

for(x=0;x<2;x++){
    arraySize = Integer.parseInt(br.readLine());

    for(i=0;i<arraySize;i++)
        array[i] = src.nextInt();
}

In this case, I am getting the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "34 12 7 4 22 15"

I am open to suggestions and am not sticking to Scanner alone. If there is any other method to achieve this, I am game.

For future reference, here's a way to do it with the Scanner class:

import java.util.Arrays;
import java.util.Scanner;


public class NumberReading {
    public static int [] readNumsFromCommandLine() {

        Scanner s = new Scanner(System.in);

        int count = s.nextInt();
        s.nextLine(); // throw away the newline.

        int [] numbers = new int[count];
        Scanner numScanner = new Scanner(s.nextLine());
        for (int i = 0; i < count; i++) {
            if (numScanner.hasNextInt()) {
                numbers[i] = numScanner.nextInt();
            } else {
                System.out.println("You didn't provide enough numbers");
                break;
            }
        }

        return numbers;
    }

    public static void main(String[] args) {
        int[] numbers = readNumsFromCommandLine();
        System.out.println(Arrays.toString(numbers));
    }
}

You said you could use the following code in C++:

for(i=0;i<6;i++) 
cin>>a[i];

If this is what you used in C++, why not just use this?

for(i=0;i<6;i++)
a[i] = input.nextInt();

Assuming that the scanner declaration was:

Scanner input = new Scanner(System.in);

From what I've seen, people are trying to write the entire program for you. But seeing as you stated you could solve this problem using the C++ code, I just converted the code to Java for you.

If you want the full code, here it is:

import java.util.Scanner;

public class arrayFun {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Create a new array. The user enters the size
        int[] array = new int[input.nextInt()];

        // Get the value of each element in the array
        for(int i = 0; i < array.length; i++)
            array[i] = input.nextInt();

        /* Note that the user can type the following:
         * 6
         * 34 12 7 4 22 15
         * This will set the array to size 6
         * array[0] = 34;
         * array[1] = 12;
         * etc.
         */

    }

}

I realize that this response is years late, but I was searching for a different question when I ran across this. The answers here were very confusing to me until I realized this wasn't what I was looking for. Seeing as this still shows up on google, I decided to post this.

    Scanner in = new Scanner(inputFile);
    int[] ints = Arrays.stream(in.nextLine().split("\\s+"))
      .mapToInt(Integer::parseInt).toArray();

If your input is "6 34 12 7 4 22 15 3 3 6 2" separated by spaces then it will be read all in one go by br.readLine() . You can't pass "6 34 12 7 4 22 15 3 3 6 2" to parseInt , as you have seen.

For this case, I would recommend you call String.split() on the String returned by br.readLine() , and you will be left with an array of Strings which can be passed in turn to Integer.parseInt() .

您可以尝试使用StringTokenizer ,但如果您知道提前使用了哪个分隔符,只需使用String.split()

new Scanner(System.in).useDelimiter("[ ]") 

should help you avoid the problem noted by Vanathi in his answer. As for knowing the size of your array, something like :

br.readLine().split("[ ]").length;

should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM