开发者

Scanner is scanning full lines with next() and not considering spaces

开发者 https://www.devze.com 2023-01-24 19:12 出处:网络
I\'m trying to put X\'s and spaces into a 2D array and I keep having problem after problem.All I want is the text representation to be in 2D array form but when I debug I notice that some cells have f

I'm trying to put X's and spaces into a 2D array and I keep having problem after problem. All I want is the text representation to be in 2D array form but when I debug I notice that some cells have full lines in them instead of a string of one character!

If you can vis开发者_Go百科ualize the 2D array as a maze, X's being the wall and spaces being the open areas to traverse, then it will help you understand what I am doing. I just need each cell to have the proper value: an X or a " ".

 while(scan.hasNextLine() && r < rows) {
            while(scan.hasNextLine() && c < columns) {
                maze[r][c]=scan.next();
                c++;
            }
            c = 0;
            r++;
        }


If you're going to use hasNextLine() then you'll want to use nextLine() to retrieve it. If you don't care about the next line, and really want to deal with the next token, then you should be using hasNext() and next().


You could try a slightly different approach:

 while(scan.hasNextLine() && r < rows) {
   String line = scan.nextLine();
   char[] characters = line.    toCharArray();
   for (int i=0; i< characters.length; i=i+1{
        maze[r][i] = characters[i];
   }
   r++;
 }

Edit: looking at your code, I do not know if it would cause the problem you stated, but your second while loop has scan.hasNextLine() and since you are actually using scan.next() there, it should be scan.hasNext(). Also since you are potentially ending the loop early if there are any columns left in the line, maybe it is not going to the next line.

0

精彩评论

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

关注公众号