3

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.

4
  • my guess is arraySize = Integer.parseInt(br.readLine()); raises the exception ? am i right ? Commented Dec 29, 2011 at 12:51
  • 3
    StringTokenizer was THAT time consuming ? Did you profile it ? Commented Dec 29, 2011 at 12:53
  • Is this homework? If so, please add the homework tag... Commented Dec 29, 2011 at 12:56
  • I suggested StringTokenizer in my answer after skimming and missing your mention of trying it already. I, too, am curious as to why you say StringTokenizer took a long time. Did it take a long time to run or did it take a long time to program? The former might betray problems on your system. The latter will betray problems in the design of your implementation. Commented Dec 29, 2011 at 13:00

6 Answers 6

12

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));
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you need a second scanner?
For clarity and for basic validation. I wanted to make sure that the numbers the user were expecting were all on the second line and not spread about on different lines.
5

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.

Comments

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

Comments

0

You might experiment with StringTokenizer, but if you know what delimiter is being used ahead of time, just use String.split()

1 Comment

This works just fine. In fact, this is faster than the StringTokenizer method. Thanks @yock
0

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().

3 Comments

I hadn't formatted my input in the question above. Actually, the input is in 4 different lines. I have updated the input above.
Well in that case I would ignore the count lines and use the .split() approach on the lines with actual data in. Or use StringTokenizer. There's unlikely to be a performance problem here - if there is then you could restructure your input perhaps? After profiling of course.
Just re-read the question - this is data that the user types in? Then why allow them the chance to give contradictory information, like: "3" "1 2"
0
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.

1 Comment

Damn, my regex are rusty. Could very well work with just an empty space between brackets, can't test it right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.