我该怎么做才能解决这个与扫描程序相关的错误?

时间:2017-02-09 04:31:06

标签: java exception

即使此代码编译:

import java.util.Scanner; // imports the Scanner class from the java.util package

public class ScannerPractice {

public static void main(String args[]) {

    Scanner word = new Scanner("word 1 2 3 4"); // creates a new Scanner objecrt with a string as its input
    String scaStr = word.nextLine(); // converts scanner to string

    String strArr[] = new String[10];
    // as long as the scanner has another character...
    for (int i = 0; i < scaStr.length(); i++) {

        int j = 0;
        String k = "";
        // if the next token is an integer...
        if (word.hasNextInt()) {

            j = word.nextInt();
            k = String.valueOf(j);
            strArr[i] = k;

        }

        // otherwise, skip over that token
        else {

            word.next();

        }

    }

    String k = "";
    // for each character in charArr
    for (int i = 0; i < strArr.length; i++) {

        // Accumulate each element of charArr to k
        k += " " + strArr[i];

    }
    System.out.print(k);

}
}

我收到此错误:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at ScannerPractice.main(ScannerPractice.java:28)

例外是指第28行,即:

word.next();

我已经尝试查看我的for循环,它将值赋给字符串数组,但我仍然找不到错误。

我正试图解决这个问题。即使是暗示也是最受欢迎的。

3 个答案:

答案 0 :(得分:1)

您已经消耗了此行Scanner中的所有字符串。

String scaStr = word.nextLine();

因此,扫描仪没有更多特征,这就是您收到错误的原因。

我认为您不需要将扫描仪转换为字符串&#39;为了迭代它。您只需使用while检查Scanner是否还有剩余的字符。

while(word.hasNext()) {
   int j = 0;
   String k = "";
   // if the next token is an integer...
   if (word.hasNextInt()) {
        j = word.nextInt();
        k = String.valueOf(j);
        strArr[i] = k;
   }
   // otherwise, skip over that token
   else {
       word.next();
   }
}

答案 1 :(得分:0)

更改循环以检查扫描程序是否还有输入:

Scanner word = new Scanner("word 1 2 3 4");
String strArr[] = new String[10];
int i = 0;

while (word.hasNext()) {
    int j = 0;
    String k = "";

    if (word.hasNextInt()) {
        j = word.nextInt();
        k = String.valueOf(j);
        strArr[i] = k;
    }
    else {
        word.next();
    }
}

迭代扫描仪已经消耗的字符串是没有意义的,因为这样就失去了匹配令牌的能力。如果你想使用字符串标记器,你可以这样做,但是你可以使用扫描仪。

答案 2 :(得分:0)

如果您希望代码正确运行,请将输入更改为:

Scanner word = new Scanner("word"+"\n"+"1"+"\n"+"2"+"\n"+"3"+"\n"+"4");

添加换行符可以解决问题。