我应该怎么做才能解决这个扫描仪相关的错误?

问题描述:

即使代码编译:我应该怎么做才能解决这个扫描仪相关的错误?

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循环将值赋给字符串数组,但我仍然找不到错误。

我正在试图解决这个问题。即使是一个暗示,将不胜感激。

+0

根据文档,扫描程序抛出,如果你调用'next()'并且没有更多的标记可用。而且,他们不可用,因为他们还没有打字,我想。 –

+0

你的代码没有任何意义,因为你创建了一个可以处理令牌的扫描器,但是然后遍历一个扁平的字符串。那么,你想使用扫描仪或使用常规字符串进行标记吗? –

+0

想一想,如果你为你的循环使用'scaStr.length()',你会经历多少次迭代。如果你真的只是试图解析你的字符串中的所有内容,那么你可以使用'word.hasNextInt()'来确定你是否想继续前进。 – Dana

您已经使用了此行上Scanner中的所有字符串。

String scaStr = word.nextLine();

因此,扫描仪没有更多characteres,这就是为什么你得到这个错误。

我认为你不需要'将扫描器转换为字符串'来迭代它。您可以简单地使用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(); 
    } 
} 

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

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

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