Scanner within scanner error

When trying to scan a text file and then scan each individual line in the text file to create an object I get the error below. Any idea on how I can fix this?

Error: java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at MyZoo.readDataFromFile(MyZoo.java:111)

while(scanner.hasNextLine()){
    lineOfInput = scanner.nextLine();
    if(lineOfInput.startsWith("#")){

    } else {
        String animalType, species, name;
        Scanner newScanner = new   Scanner(lineOfInput).useDelimiter("s*,s*");

        animalType = newScanner.next();
        System.out.println(animalType);
        species    = newScanner.next();
        name       = newScanner.nextLine();
   }

As you said in a comment

"It is a text file containing lines of data, I read in the line using the 1st scanner. Then trying to scan each word in the line read in to assign them as variables. After I scan in the first 3, I want it to be read the rest of the data in the animal specific class "

your second scanner uses a wrong delimiter, due to which you are getting that exception.

try :

Scanner newScanner = new   Scanner(lineOfInput).useDelimiter("W");

Hope this helps.


我认为你可以这样做:

while (scanner.hasNextLine()) {
    lineOfInput = scanner.nextLine();
    if (lineOfInput.startsWith("#")) {

    } else {
        String animalType, species, name;

        String s[] = lineOfInput.split(" ");
        animalType = s[0];
        species = s[1];
        name = s[2];
    }

}
链接地址: http://www.djcxy.com/p/17220.html

上一篇: Scanner的意外行为

下一篇: 扫描仪内的扫描仪错误