开发者

What's wrong with my loop? Keep getting NoSuchElementException

开发者 https://www.devze.com 2023-01-24 18:59 出处:网络
I keep getting a NoSuchElement Exception at the line maze[r][c]=scan.next();. How can I resolve that?

I keep getting a NoSuchElement Exception at the line 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 (Fi开发者_JS百科leNotFoundException 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. But in line 3, you read that line - inside the 2:4 loop. 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. 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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消