有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文件扫描二维字符串数组

Scanner input = null;
    try {
        input = new Scanner (new File(filename));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
    }
    int m = 4;
    int n = 4;
     Puzzle = new String [m][n];
    while (input.next()!=null){
        for (int i=0;i<m;i++){
            for (int j=0;j<n;j++){
                Puzzle[i][j]= input.next();
                System.out.println(Puzzle[i][j]);
            }
        }   

    }

I have a little problem with this piece of code. as I scan the input to put my puzzle array it skips the first string. for example in the first line, lets assume the 4 letter "A B C D" are on. It skips the "A" and continues with "B". I know maybe its too easy for you guys, but as a begginner I kinda need your help.


共 (1) 个答案

  1. # 1 楼答案

    您在while循环的每次迭代中使用多个令牌-在循环条件下调用next()(未使用)时使用一个令牌,在for循环(存储)内调用next()时使用多个令牌

    您应该更改代码的逻辑。你不需要while循环

    例如:

        boolean done = false;
        for (int i=0;i<m && !done;i++){
            for (int j=0;j<n && !done;j++){
                Puzzle[i][j]= input.next();
                if (Puzzle[i][j] == null)
                    done = true;
                System.out.println(Puzzle[i][j]);
            }
        }