thesaxo wrote
Hello, i'm trying to develop a very simple rock, paper, scissors game, but i'm struggling with the syntax of Jack, and i can't understand why this loop never ends:
class User {
function void choose() {
var String choice;
while (~((choice = "ROCK") | (choice = "PAPER") | (choice = "SCISSORS"))) {
let choice = Keyboard.readLine("Pick ROCK, PAPER or SCISSORS: ");
do Output.printString(choice);
do Output.println();
}
do Output.printString("You choosed ");
do Output.printString(choice);
do Output.println();
do String.dispose(choice);
return;
}
}
I tryed typing 'ROCK', or 'rock' and so on but it doesn't change.
You've got a few issues.
First, when you declare a variable you are only allocating memory for that variable. An variable of object type (such as String) is a one-word (16-bit) variable whose value is the address where the object is stored. Jack initializes local variables to 0, so at the start of your loop 'choice' is equal to 0 (and there is no String object stored there -- in fact it's where the Stack Pointer is located).
Next, when you use an expression such as
while (choice = "ROCK")
The compiler inserts code to create a string object and replaces the literal string in the source code a call to the String object constructor and additional code to copy the string into the allocated object. Since a constructor returns the address where the object it constructed is stored, what you are doing is comparing the addresses of two objects. Even if the contents are identical, they are not the same object and their address will only be equal if they are.