I'm finishing up a project due by midnight today. I'm supposed to make a Guessing game using a bit of object-oriented programming. I've got it pretty much done, except for one part.
I need to make the program loop if you want to do a replay. The example here in the assignment says:
Play again? Y/N:
you input Y or N if you want to replay, or don't want to replay. We're assuming there is no human error here. I tried to create a large while loop around the game program, like this:
(this is the runner class, handles user input)
int rLoop = 0;
while (rLoop = 0) {
-game stuff here-
rLoop = n.replay(replay);
}
(this is the Game class, handles aspect of the game)
int replay(String Replay) {
if (Replay == "Y") {
return 0;
} else {
return 1;
}
}
It quits whenever I put Y or N. Doesn't matter what I put, really. I need to figure out how to make the code recognize if i put Y or N, and change an integer according to it to stop/continue the loop.
Ok first, Shouldn't the while loop condition at the top be rLoop == 0 instead rLoop =0. And also the mistake your making is that you can never compare two String directly with a relational operator. You are required to use some sort of method from the String class.In this case you would use the equals method which compares two string and determines if they are equal by returning a boolean value.
don't do == with strings, always use .equals(), for example:
String s1 = "example";
String s2 = "example";
boolean b = s1.equals(s2);
so your function would look like this:
int replay(String Replay) {
if (Replay.equals("Y") {
return 0;
} else {
return 1;
}
since you're only using 0 or 1 i'd advice to make the function return a boolean and to change your 'rLoop' variable into a boolean, so your game would look like this
I suspect the teacher was really looking for a do { ... } while (...); loop. Of course other ways will work too, but the point is to have the test at the end, where it most makes sense.