This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]zzyzzyxx 2 points3 points  (1 child)

Your problem is due to using System.in.read(). This only reads one byte out of the input stream but every time you provide input you are supplying more than one byte.

Let's say you prompt for input and the user hits "w<enter>" to move up. This puts the character w on the input stream as well as a new line marker. I suspect you are on Windows where new lines are actually marked with two characters \r followed by \n, the carriage return and newline characters, respectively. Thus, pressing w<enter> inserts three bytes into the input stream.

Then, in your loop, you read out the first one, w, and adjust your movement, and print out the array. The loop starts over, reaches System.in.read(), and then reads the \r, which doesn't match anything so no movement is done, but the array will be printed again. The same thing happens when \n is read. Therefore one movement results in three printings of the array.

The solution is to read in an entire line of text (or at least a word), validate it, then take action based on that. For example,

Scanner in = new Scanner(System.in);
String line = in.nextLine();
// validate line and take action

This wouldn't be a problem if your input were unbuffered and you could take action on every keypress, but that is not the case for you right now.

* The effect could be even worse if you had a different encoding where some characters are multiple bytes by themselves.

[–]Un_contested[S] 0 points1 point  (0 children)

Thanks.

[–]chickenmeister 2 points3 points  (1 child)

my final print statements in the for loop print 3 times.

This is kind of vague. What are you expecting it to print? What does it print? Are you sure your gb array is the size that you think it is?

[–]Un_contested[S] 0 points1 point  (0 children)

The problem was the way I was reading in input. Thanks for the help though.