0

I'm doing Homework and I'm inputting values via the console using. The program is not nearly finished and I'm just trying to get the input system to work. I'm running into a problem where I've seen other people run into with other pieces of code but I don't know how to implement them in this context.

It's inputted in this format: 4 - number of lines of data 5 6 - Datapeices 5 6 - Datapeices 5 6 - Datapeices 5 6 - Datapeices

I'm trying to make an array w/ line 1 * 2 length and proceed to stor that in the array. Every other datapeice I'm going down a line.

import java.io.*;

import java.util.StringTokenizer;

    int arr[];
    int x = 0;

    BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());
    arr = new int [Integer.parseInt(st.nextToken())*2];

    for (int i = 0; i < arr.length; i++) {
        if ((i%2)==1) {
            x = Integer.parseInt(st.nextToken());
            st = new StringTokenizer(br.readLine());
        } else {
            x = Integer.parseInt(st.nextToken());
        }
        arr[i] = x;
    }
    System.out.println(arr.toString());
}
Brandon Li
  • 17
  • 1
  • 7
  • Could you provide a sample of your input and indicate where in this code the error is occurring? – Chris K May 01 '19 at 23:37
  • 1
    See [MCVE](https://stackoverflow.com/help/mcve). Also, consider using the `split()` method of String, which is what most devs would use because it’s simpler. – Bohemian May 01 '19 at 23:38
  • @ck1221 the input is 4, 2 4, 1 1 ,5 2, 17 25 and the error is happenning right after I input the values into the console and hit enter – Brandon Li May 01 '19 at 23:39
  • Possible duplicate of [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Benjamin Urquhart May 02 '19 at 00:01

1 Answers1

0

I see 3 problems in the code:

  1. You try to initialise an array with a strange size. new int [Integer.parseInt(st.nextToken())*2] -> new int [st.countTokens()]

  2. In if the condition you try to read nest line from a console, and it can be empty. But you try to read the next token when there are no tokens. And the problem in st = new StringTokenizer(br.readLine()); - so you must add check: st.hasMoreTokens(). You can put it in for statement.

  3. As I suppose you want to print array content with toString() - it doesn't work as you expect. Use System.out.println(Arrays.toString(arr));