简体   繁体   English

如何修复java.util.NoSuchElementException

[英]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 它以这种格式输入:4 - 数据行数5 6 - 数据表5 6 - 数据表5 6 - 数据表5 6 - 数据表

I'm trying to make an array w/ line 1 * 2 length and proceed to stor that in the array. 我正在尝试使用1 * 2行的数组生成一个数组并继续在数组中进行存储。 Every other datapeice I'm going down a line. 其他所有数据文件我都会排成一行。

import java.io.*; import java.io. *;

import java.util.StringTokenizer; 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());
}

I see 3 problems in the code: 我在代码中看到3个问题:

  1. You try to initialise an array with a strange size. 您尝试初始化具有奇怪大小的数组。 new int [Integer.parseInt(st.nextToken())*2] -> new int [st.countTokens()] 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()); st = new StringTokenizer(br.readLine()); - so you must add check: st.hasMoreTokens() . - 所以你必须添加check: st.hasMoreTokens() You can put it in for statement. 你可以把它放在for声明。

  3. As I suppose you want to print array content with toString() - it doesn't work as you expect. 我想你想用toString()打印数组内容 - 它不会像你期望的那样工作。 Use System.out.println(Arrays.toString(arr)); 使用System.out.println(Arrays.toString(arr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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