简体   繁体   English

我的循环怎么了? 不断收到NoSuchElementException

[英]What's wrong with my loop? Keep getting NoSuchElementException

I keep getting a NoSuchElement Exception at the line maze[r][c]=scan.next(); 我在maze[r][c]=scan.next();行中不断收到NoSuchElement Exception maze[r][c]=scan.next(); . How can I resolve that? 我该如何解决?

  try {
        Scanner scan = new Scanner(f);
        String infoLine = scan.nextLine();
        int rows=0;
        int columns=0;
        for(int i = 0; i<infoLine.length();i++){
            if(Character.isDigit(infoLine.charAt(i))==true){
                rows = (int)infoLine.charAt(i);
                columns = (int)infoLine.charAt(i+1);
                break;
            }
        }

        String [][] maze = new String[rows][columns];
        int r = 0;
        while(scan.hasNextLine()==true && r<rows){
            for(int c = 0; c<columns;c++){
                maze[r][c]=scan.next();
            }
            r++;
        }
        return maze;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Look at this part of your code: 看一下这段代码:

    while(scan.hasNextLine()==true && r<rows){  // 1
        for(int c = 0; c<columns;c++){          // 2
            maze[r][c]=scan.next();             // 3
        }                                       // 4
        r++;                                    // 5
    }                                           // 6

In line 1 you are checking to make sure that scan has another line available. 在第1行中,您正在检查以确保扫描还有另一行可用。 But in line 3, you read that line - inside the 2:4 loop. 但是在第3行中,您会读到该行-在2:4循环内。 So if there are more than 1 columns, you will be asking for the next scan more than once - and you only checked to see if there was one next line. 因此,如果有多于1列,您将不止一次地要求进行下一次扫描-并且仅检查是否存在下一行。 So on the second column, if you're at the end of scan, you try to read from scan even though it's run out. 因此,在第二列上,如果您处于扫描的结尾,即使扫描用完了,您也尝试从扫描中读取。

Try this: 尝试这个:

try {
    Scanner scan = new Scanner(f);
    String infoLine = scan.nextLine();
    int rows = 0;
    int columns = 0;
    for (int i = 0; i < infoLine.length();i++) {
        if (Character.isDigit(infoLine.charAt(i))) {
            rows = Character.digit(infoLine.charAt(i), 10);
            columns = Character.digit(infoLine.charAt(i + 1), 10);
            break;
        }
    }

    String [][] maze = new String[rows][columns];
    int r = 0;
    while(scan.hasNextLine() && r < rows) {
        int c = 0;
        while(scan.hasNextLine() && c < columns) {
            maze[r][c]=scan.next();
            c++
        }
        r++;
    }
    return maze;
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

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

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