Search code examples
javastringtokenizer

How to fix java.util.NoSuchElementException


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

Solution

  • 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));