简体   繁体   中英

What's wrong with my loop? Keep getting NoSuchElementException

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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