This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Filling an Array.

 
Shaggy Rogers
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the following code gets me stuck in an infinite loop, not sure why.

while(input.hasNext())
{
for(int i = 0; i < maze.length; i++)
{
for(int x = 0; x < maze[i].length; x++)
{

String insert = input.nextLine();

maze[i][x] = insert.charAt(x);
}
}
}
What I'm trying to do is read the characters on the line and fill them in the maze[][] (of type char) array. Not sure why this code isn't working like it should be.
 
Shaggy Rogers
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've also tried hasNextLine instead of just hasNext, still getting the same problem.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is input ? If it is a class that blocks on a call to nextLine() if there is no more input, then it may just be sitting there waiting.
You do realise you are doing several calls to nextLine() (one for each time thru the inner loop) for each call to hasNext() that you do, so it's possible you call nextLine() when hasNext() would have returned false.
 
Shaggy Rogers
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Input is a scanner, this is what my entire constructor looks like.

public Maze(String fileName) {

//Scanner to read file

Scanner input = null;
try{
input = new Scanner(fileName);
}catch(RuntimeException e) {
System.err.println("Couldn't find the file");
System.exit(0);
}
//Set the size of the maze
while(input.hasNextInt())
{
size = input.nextInt();
}

//Set Limits on coordinates
Coordinates.setLimits(size);

//Set the maze[][] array equal to this size
maze = new char[size][size];

//Fill the Array with maze values

for(int i = 0; i < maze.length; i++)
{
for(int x = 0; x < maze[i].length; x++)
{
if(input.hasNextLine())
{
String insert = input.nextLine();

maze[i][x] = insert.charAt(x);
}
}
}



}
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never used Scanner so this is just a guess, but the Javadoc for the nextXXX methods says This method may block while waiting for input.
I would be tempted to put some print statements in to your code to see if you can find where it is looping/blocking.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic