Reputation: 67
part of my code where you can play a puzzle with the idea of retuning a shuffled 4x4 number array back to its original state. the user enters certain command e.g. row 0 row 1, and a loop does the command, prints the latest puzzle then asks for the command and should end when the puzzle matches the original state of the puzzle. my loop never breaks when back to the original puzzle and constantly prints invalid input even when correct input has been entered. how can i fix these problems? this is just the play method part of the code
static void play(int[][] puzzle) {
reset(puzzle);
int[][] z = new int[N][N];
reset(z);
print(puzzle);
for (int i = 0; i < 5; i++) {
randomRotation(puzzle);
}
print(puzzle);
while (puzzle!=z) {
System.out.println("enter row x or col x: ");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
if (!x.equals("row 0") || !x.equals("row 1") ||!x.equals( "row 2") ||!x.equals( "row 3") ||!x.equals( "col 0") ||!x.equals( "col 1") ||!x.equals( "col 2") ||!x.equals("col3")) {
System.out.println("invalid input");
}
if (x.equals("row 0")) {
rotateRow(puzzle, 0);
print(puzzle);
}
if (x.equals("row 1")) {
rotateRow(puzzle, 1);
print(puzzle);
}
if (x.equals("row 2")) {
rotateRow(puzzle, 2);
print(puzzle);
}
if (x.equals("row 3")) {
rotateRow(puzzle, 3);
print(puzzle);
}
if (x.equals("col 0")) {
rotateColumn(puzzle, 0);
print(puzzle);
}
if (x.equals("col 1")) {
rotateColumn(puzzle, 1);
print(puzzle);
}
if (x.equals("col 2")) {
rotateColumn(puzzle, 2);
print(puzzle);
}
if (x.equals("col 3")) {
rotateColumn(puzzle, 3);
print(puzzle);
}
}
}
Upvotes: 0
Views: 62
Reputation: 4707
You have a few issues and inefficiencies in your code, but this is the problem you're asking about: Your while should be !puzzle.equals(z)
instead of puzzle!=z
. Arrays are not primitives and as such two different declarations of arrays, even if their contents are the same, will never be equal by memory (==
).
Also, you should make all of your if
s into else if
s and move the invalid input to the bottom as an else
. The else
will then correct your problem of using ors instead of ands.
Upvotes: 0
Reputation: 1641
Your Boolean is backwards. Saying "is not ... or is not ... or is not ..." So unless it's Schroedinger's cat and is all those values at the same time, the test will always succeed.
Upvotes: 1
Reputation: 2953
Use a continue
after System.out.println("invalid input");
.
Upvotes: 1