Java 我应该如何修复此扫描仪相关的错误?

Java 我应该如何修复此扫描仪相关的错误?,java,exception,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 wit

即使此代码编译:

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

}
}
例外情况涉及第28行,即:

word.next();
我尝试查看为字符串数组赋值的for循环,但仍然找不到错误


我绞尽脑汁想解决这个问题。即使是一个提示也非常感谢。

您已经在这一行中使用了
扫描仪中的所有字符串

String scaStr=word.nextLine()

因此,扫描仪没有更多的字符,这就是为什么会出现错误

我认为你不需要“将扫描器转换为字符串”来迭代它。您只需使用
while
检查
扫描仪是否有剩余字符

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

更改循环以检查扫描仪是否有更多输入:

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

迭代扫描程序中已经使用的字符串是没有意义的,因为这样您就失去了匹配标记的能力。如果您想使用字符串标记器,您可以这样做,但可以使用扫描仪删除。

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

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

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

根据文档,如果调用
next()
并且没有更多的令牌可用,Scanner会抛出这个问题。我认为,它们不可用是因为它们还没有被键入。您的代码毫无意义,因为您创建了一个可以处理令牌的扫描程序,但随后在一个平面字符串上迭代。那么,您想使用扫描器还是使用常规字符串进行标记化?如果您使用循环的
scaStr.length()
,请考虑您将经历多少次迭代。如果您只是试图解析字符串中的所有int,那么可以使用
word.hasNextInt()
来确定是否继续。
Scanner word = new Scanner("word"+"\n"+"1"+"\n"+"2"+"\n"+"3"+"\n"+"4");