Initialising Issue - java

private void northroom()
{
char choice2;
boolean boolean_1 = false;
String answer2;
System.out.println("You press a panel next to the door");
System.out.println("The panel lights up with a pinging sound");
System.out.println("The door slowly scrapes open");
System.out.println("You are now in North Room");
System.out.println("There is a object in the coner of the room shoraded by darkness");
do
{
System.out.println("Would you like to pick up object Yes(Y) or No(N)");
while(boolean_1 == false)
{
answer2 = keyboard.next();
choice2 = answer2.charAt(0);
if(choice2 == 'Y')
{
System.out.println("You go pick up the object");
}
if(choice2 == 'N')
{
System.out.println("Stare at object because you are useless");
System.out.println("Try again");
}
}
}
while (**choice2** != 'Y' && **choice2** != 'N');
while (choice2 != 'Y' && choice2 != 'N');
Here both the choice2 are initialised how do I correct this so that it loops properly

The compilers code-path analyzer doesn't go far enough to recognize that the while(boolean_1 == false) loop will always execute at least once.
As far as the compiler is concerned, the loop body might be skipped, in which case the choice2 variable is unassigned, i.e. not definitely assigned.
You can fix that by initializing it to a dummy value, e.g.
char choice2 = ' ';
Of course, if the compiler did extended analysis, it would have found that the while(boolean_1 == false) loop runs forever, since boolean_1 is never updated, and would have generated compile error saying that while (choice2 != 'Y' && choice2 != 'N'); is unreachable.

I'm not sure what is the designed behavior for your nested loops. However, ur inner loop is a infinite loop. It can never end so outer loop can never check condition showed in last line of code

Related

Looping a 2 player rock paper scissors game (Java)

im trying to create a 2 player rock paper scissors game with a prompt to continue or end the game. and also re-ask for your move if entered incorrectly. i've been trying to use do-while loops but i get an error every time.
it doesn't recognize the do-while i put in, because it's not reading the while(playAgain.equals("Y");
let me know what i can fix and where i should start my do and start my while. thanks!
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
//player one input
Scanner in = new Scanner(System.in);
//loop start?
do {
System.out.println("Player One, please enter your move [R/P/S]: ");
String playerOne = in.nextLine();
//verify move is valid
if (!playerOne.equals("R") && !playerOne.equals("P") && !playerOne.equals("S")) {
System.out.println("Invalid input, please enter valid move.");
} else {
//player two input
System.out.println("Player Two, please enter your move [R/P/S]: ");
String playerTwo = in.nextLine();
//verify move is valid
if (!playerTwo.equals("R") && !playerTwo.equals("P") && !playerTwo.equals("S")) {
System.out.println("Invalid input, please enter valid move.");
}
//game outcome
if (playerOne.equals(playerTwo)) {
System.out.println("You tied!");
} else if (
(playerOne.equals("R") && playerTwo.equals("S")) ||
(playerOne.equals("S") && playerTwo.equals("P")) ||
(playerOne.equals("P") && playerTwo.equals("R"))) {
System.out.println("Player One has won!");
} else if (
(playerTwo.equals("R") && playerOne.equals("S")) ||
(playerTwo.equals("S") && playerOne.equals("P")) ||
(playerTwo.equals("P") && playerOne.equals("R"))) {
System.out.println("Player Two has won!");
}}}//loop end?
while (playAgain.equals("Y"));
//prompt user to play again
System.out.println("Would you like to play again? [Y/N]");
String playAgain = in.nextLine();
if (playAgain.equals("N")) {
System.out.println("Game stopped. Thanks for playing!");
}
if (!playAgain.equals("Y") && !playAgain.equals("N")) {
System.out.println("Invalid input, please enter valid response.");
}}}
I will look further, though to improve readability|simplify logic
if (!playerOne.equals("R") && !playerOne.equals("P") && !playerOne.equals("S"))
is the same as
if (!((playerOne.equals("R") || playerOne.equals("P") || playerOne.equals("S")))
EDIT: In your logic, I don't see a case for asking the player again. This can/will lead to a logic hole.
bool inPlay = true;
while(inPlay)
{
...
if(valid plays)
{
if(tie) print tie;
else if(p1 wins) print player1;
else if(p2 wins) print player2;
inPlay = ask: want to play again?
}else
{
tell them it is invalid, loop again;
}
...
}
^This will allow you to ask again
EDIT 2: for a do-while, it is essentially the same deal:
bool inPlay = true;
do
{
above logic;
}while(inPlay);
EDIT 3: With your most recent version I see a vital flaw here:
do
{
...
}
while (playAgain.equals("Y"));//<-- semicolon
//prompt user to play again
System.out.println("Would you like to play again? [Y/N]");
...
You can't go back to the start of the do-while loop with that prompt after the semicolon ; has been reached. You need to ask that question within the curly brackets {} after the game has been finished.
EDIT 4: to expand on OP's "I'm getting an error that my playAgain variable is not initialized even when I add String playAgain;"
String playAgain = "";
do
{
...
playAgain = their answer;
...
}while(playAgain.equals("Y"));
However, I don't think you need to keep the String outside the scope of the loop, a boolean is all you need, and a boolean is easier to read. So perhaps:
//See EDIT 2 above
...
// will result in true for Y and false for !Y
playAgain = (answer == 'Y')
...

While loop not working according to the condition in Java

I am trying to build a Number guessing game which has a while loop with 2 conditions in it. However even after 1 of those 2 conditions become false then also the loop keeps going on even though I have || operator between those conditions. Also if I clear out the first condition of while loop then the second one works just perfectly as I want it to but if it is present then idk why it doesn't stop. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String args[]) {
Random num = new Random();
int number = 1 + num.nextInt(10);
Scanner inp = new Scanner(System.in);
boolean guessed = false;
System.out.println("Welcome to Number guess!");
int guess_count = 5;
while(guessed == false || guess_count > 0 ) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
guessed = true;
}
else {
System.out.println("Nope!");
guessed = false;
guess_count--;
System.out.println("Guesses left: " + guess_count);
}
}
}
}
When counter goes below 0 then also the loop keeps going on but I don't want it to.
Please tell me where am I wrong.
You don't need an OR operator. What you need is an AND operator. Means your condition should be (guessed == false && guess_count > 0 ).
WHY?
Because the OR conditional operator works if either the condition is true, in your case if the user unable to guess 5 times then your guessed variable is still false while your guess_count is less than zero, so your one condition is true. The AND operator checks for both the condition.
The condition of your while loop should be changed from an OR || to an AND &&. Currently, the || will allow execution if either guessed == false OR guess_count > 0. Only one of these conditions must be true for the while loop to continue executing.
while(guessed == false && guess_count > 0 ) {
Change to an AND && means that if the number is guessed correctly, guessed will now be true and the while loop will halt after that iteration. I was not getting any errors for when the guess_counter dropped below zero. Try it again to be sure.
Consider modifying your loop like this:
while(guess_count > 0 ) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
break;
}
else {
System.out.println("Nope!");
guessed = false;
guess_count--;
System.out.println("Guesses left: " + guess_count);
}
}
OR just modify you condition like this:
while(!guessed && guess_count > 0 ) {
You can correct your code by replacing || with &&. Why use an extra flag variable when you have guess_count decrementing to check for number of guesses. The program will terminate after guessed number is equal to the input. Here is simple implementation:
while(guess_count-->0) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
guessed = true;
break; // The user has already guessed the number no need to guess more
}
else
System.out.println("Nope!\nGuesses left: " + guess_count);

Looping if and else statements in java

I'm working on this program that asks for model numbers of cars infinitely until the person inputs 0 to break the loop. When i run it and input a number it just infinitely loops either your car is defective or it is not defective until it crashes. I'm pretty stuck right now any help would be greatly appreciated.
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
while (modelNum != 0) {
if (modelNum >= 189 && modelNum <= 195) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 189 || modelNum == 221) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 780) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
if (modelNum == 0) {
System.out.println("end");
break;
}
}
It's because you never ask the user for another input. You should do so before the end of the loop.
Include the this part into your loop:
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
You have to ask for a new value to be evaluated:
while (modelNum != 0) {
// if conditions
modelNum = input.nextInt();
}
Also note that:
if (modelNum == 0) {
System.out.println("end");
break;
}
won't be necessary because if the last value is 0 the condition in the while loop will be false and won't loop again.
Last thing: why you have all those if-else-if when they all do the same thing (print "Your car is defective it must be repaired"). This will be enough:
while (modelNum != 0) {
if ((modelNum >= 189 && modelNum <= 195) || modelNum == 221 || modelNum == 780 || modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
modelNum = input.nextInt();
}
if you enter 0, the loop will break, therefore the last if statement will never run.
This loop just tells you if the car is defective or not depending on the model number, but you never tell the program to exit the loop if the car is defective. To do so you have to put break statements into each if statement of the loop.
Moreover this statement is useless:
if(modelNum == 0)
{
System.out.println("end");
break;
since if u enter 0 the loop won't start.

Having difficulty ignoring case sensitivity for do while loop

Trying to let the user exit the program using the letter 'N' or 'n' but it will only let them exit when using 'N'
Below is my code, any help is appreciated!!
System.out.print(" Do you want to repeat the ");
System.out.println("program ['Y' or 'N']");
Choice = sc.next().charAt(0);
} while (Choice != 'N' || Choice != 'n');
}
}
You have to use while (Choice != 'N' && Choice != 'n'); .
It must be AND condition. Not an OR condition.
You are using the wrong operator:
while (Choice != 'N' && Choice != 'n');
Right now, your code states that the loop will continue when the character is either not 'N' or not 'n'. Since the character can't be 'N' and 'n' at the same time, the loop will always continue. Switching the operator to a && requires that the character is neither N nor n to continue.

Need to get the entire thing in a loop, which loop is best suited? Where should I apply it?

I am nearly finished with a Java project of mine. The objective is to play a game of Rock Paper Scissors with the user and the computer. The computer generates a random number and that number must correlate with either one of the three choices. I got it to where it can play successfully, but here is the catch, in the case of a tie, the game is to repeat and start over, otherwise it is to terminate. I have it to where it terminates, but cannot figure out how to get it to repeat the entire process in the case of a tie. The methods must remain the way they are, but my professor said the answer is if the entire thing is in a loop. My question is which loop should I use and where should it be placed? Here is the code:
public class FahrDylanRockPaperScissors{
public static void main (String [] args){
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
public static String computerChoice( ){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println ("Let's Play a game! Rock, Paper, Scissors!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + "\nPlease enter either Rock, Paper, or Scissors: " + "\nGood Luck!");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static void determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 )
System.out.println(" Tie! the game must be played again.");
}
}
You can use a do-while loop, because your code needs to be executed at least one time.
public static void main (String [] args){
boolean win = false;
do{
String computer = computerChoice();
String user = userChoice();
win = determineWinner(computer, user);
}while(!win);
}
For the first time you execute the whole code. Then the predicate is checked, and if someone won, the do-while will stop. But if win equals false it will be executed again.
You could achieve the same with only a while loop, or other loops. But because your code needs to be run at least one time a do-while suits well.
Edit:
You need to change your code, so that determineWinner returns back if someone won (return true) or if there is a tie (return false). I did not see that it currently has no return type when posting the answer.
A simple way to get the determineWinner method to work would be the following.
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 ){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
And for your coding style:
It's good practice to use brackets {} for if/else/for... even if you have only one statement, because it improves the readability of your code.
Edit 2:
Because you can't change something, the easiest way is probably the following:
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
Even if determineWinner determines the winner you need it to give you feedback. If you can't get feedback, just determine if there will be a tie in your main-Method, and if you get a tie, repeat.
You could easily just make the three lines:
public static void playGame()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
into one new method, something like playGame(). Then in the main function, you can call playGame(), and at the end of determineWinner(), you could have:
else if (computer.compareTo(user) == 0 )
{
System.out.println(" Tie! the game must be played again.");
playGame();
}
to play the game again.
Also, make sure you include the import statements for Random and Scanner. And make sure you close your scanner.
Use a flag for tie, something like this:
boolean tie = false;
combine with do while:
do {
} while (tie);
if tie == true than keep going until its false.
A do { ... } while () loop would be most natural for this problem, but pretty much any loop construct could serve.
Although you say
The methods must remain the way they are
you cannot do it if the determineWinner() method remains exactly as it now is. That method needs one way or another to communicate back to main() whether there is a tie, or else it must itself manage running a new game in the event of a tie. Were I free to do so, I would have it return a a boolean value indicating whether there was a tie. If it cannot be modified to return a value, then the other alternative would be for it to set a static variable to indicate whether there was a tie. Alternatively, you could solve this problem with recursion, but that would not involve a loop.

Categories

Resources