Why does my do while loop keep going? - java

I'm trying to do a simple Hangman game for school.
In the beginning the user inputs a word as a String and the string is converted into a char Array, wordArray. Then a char Array starArray is created that has the same amount of elements as wordArray, and is filled with "*". Those start get replaced with letters as the letters are guessed correctly.
After this, I have this loop:
do {
System.out.println("Guess a letter:");
strGuess = scan.nextLine();
chGuess = strGuess.charAt(0);
//prompts the user to guess a letter and converts said letter to a char
for(int i = 0; i<Array.getLength(wordArray); i++){
if (chGuess == wordArray[i]){
starArray[i] = strGuess.charAt(0);
guessCorrect = true;
}
} //this happens if the guess is correct
if (guessCorrect == false){
System.out.println("Nope, wrong guess!");
wrongGuess = wrongGuess + 1;
System.out.println("You have " + (5-wrongGuess) + " lives left.");
} //if the guess isn't correct, amount of wrong guesses increases
guessCorrect = false; //the value of whether a guess is correct resets
for(int i=0;i<starArray.length;i++){
System.out.print(starArray[i]);
} //prints out the word with "*" in place of letters that haven't been guessed yet
/*if starArray == wordArray
wordGuessed = true;*/
} while (wrongGuess == 5 || wordGuessed == false); //if the word is guessed or the user has guessed wrong 5 times, the loop ends
Now this code isn't complete yet, so the "wordGuessed" part of the condition can never happen as of now - you can't win the game yet. However, the loop doesn't end when the wrongGuess value gets higher than 5. It will keep going, prompting the user to guess again and again. I checked and the wordGuessed value does in fact change correctly, do it does reach 5 after 5 wrong guesses.

If wordGuessed is always false, wordGuessed == false will always return true.
The condition to loop is that wrongGuess == 5 || wordGuessed == false is true.
Using the first statement, that could be replaced by: wrongGuess == 5 || true
That will also always be true as anything OR true is true.
You want to stop looping once (wrongGuess == 5 or wordGuessed == true).
In other words, loop while !((wrongGuess == 5) OR (wordGuessed == true)).
Basic boolean algebra, the reverse of A OR B is !A AND !B. You have to keep looping while wrongGuess != 5 && wordGuessed == false

Related

data validation using char != not working [duplicate]

This question already has answers here:
Java char comparison does not seem to work [duplicate]
(2 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
Hello I know this is so basic but I am having trouble in comparing char specifically with the !=. Whenever I input other letter (not y and n) code still loop.
I tried changing the != to == and when i press Y it gets out of loop.
How is this happening? Thank you!
public static void main(String[] args) {
char inputChar;
Scanner input = new Scanner(System.in);
do {
System.out.println("-----------------------------------------------");
System.out.println("Try Again(Y/N)? ");
do {
inputChar = input.next().toUpperCase().charAt(0);
System.out.println("Loop");
} while (inputChar != 'Y' || inputChar != 'N');
System.out.println(inputChar + " d");
} while (inputChar == 'Y');
System.out.println("Thank you and Good bye!");
}
while (inputChar != 'Y' || inputChar != 'N');
The condition you wrote says 'loop while the input is not Y or is not N'.
No character is equal to Y and equal to N at the same time, so this will loop forever.
If it's Y, then it's not N, so the second part is true.
If it's N, then it's not Y, so the first part is true.
If it's Z, then both parts are true.
You want
while (inputChar != 'Y' && inputChar != 'N');
The issue is with this line: } while (inputChar != 'Y' || inputChar != 'N');
Since you are using a logical or operation, the loop continues while inputChar is not equal to Y or inputChar is not equal to N. The issue is that one of these is always true so your loop runs forever since a character cannot be both equal to 'N' and to 'Y'. Try using a logical and (&&) instead.

Why is this causing a constant 'true' in this while loop?

Here is the code;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N.");
char a = input.next().charAt(0);
// This while loop always comes out as true.
while (a != 'y' || a != 'n') {
System.out.println("Please enter either Y/N. ");
System.exit(0);
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Is there an explanation on why it always comes out as true, and is there an alternative way of doing this? I want to have a validation check, where if the user inputs anything other than y, or n, the program shuts down.
The problem is, when I enter the character, y, or n, it shuts down anyway even though I'm using the != (not equals) operator.
If you have a==y, then a != 'n' is true and a != 'y' || a != 'n' is true.
If you have a==n, then a != 'y' is true and a != 'y' || a != 'n' is true.
If you have a == other thing, a != 'y' || a != 'n' is true.
It is everytime true with the OR operation. Need use AND.
(a != 'y' || a != 'n') at least one of the sub-conditions must be true.
Consider the three possible cases:
a is 'y': false || true gives true
a is 'n': true || false gives true
a is something else: true || true gives true
The character a cannot both be y and n, so the while loop is executed for any input.
Besides, the loop is not looping.
You're checking whether a is not equal to 'y' OR a is not equal to 'n'.
This is always true.
Change it into while ((a != 'y') && (a != 'n')).
The condition inside while in
while (a != 'y' || a != 'n')
is always true because
if a is equal to y, then a is obviously not equal to n. So, result is true.
And again, if a is equal to n, then a is obviously not equal to y. So, result is true.
And again, if a is not equal to y or n, then also the result is true.
So, the condition inside the while is always true. And for this reason, the execution is entering the while loop and after printing your message it is exiting.
So using AND instead of OR may solve your problem, like
while(a != 'y' && a !='n') {
//your work
}
And I think you willing to do this like below,
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N: ");
char a = input.next().charAt(0);
while (a != 'y') {
if(a =='n') {
System.exit(0);
}
else{
System.out.println("Please enter either Y/N : ");
a = input.next().charAt(0);
}
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Your logic should be "a is not y and a is not n"
while (a != 'y' && a != 'n')

Calling an Integer into a Boolean

The section of my code that isn't working
}else if(bossOne == 3){
int bossOneHP = 70 + bossStat.nextInt(10)-5;
int bossOneOP = 27 + bossStat.nextInt(10)-5;
int bossOneBP = 12 + bossStat.nextInt(10)-5;
String bossName = "Spartan King";
waits();
System.out.println("Your first enemy is the Spartan King.");
System.out.println("It has a very powerful attack, lets hope you have enough health.");
}
boolean keepPlaying = true;
while (keepPlaying){
Scanner choice = new Scanner(System.in);
System.out.println("Enter 1 to attack.");
System.out.println("Enter 2 to block.");
System.out.println("Enter 3 to exit the game.");
int selection = choice.nextInt();
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
waits();
System.out.println("You block.");
System.out.println(HP == HP - (bossOneOP - BP));
}else if(selection == 3){
break;
}
if (bossHP == (0 || >0){
System.out.println("Congratulations you won!");
break;
}
if (HP == (0 || >0)){
System.out.println("Sorry you lost.");
break;
}
I need to have the integers be called to the section. This code is for the meat of the game I am creating for my programming class any help would be appreciated.
You want the 'greater than or equal to' operator: >=
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
if (HP >= 0){
System.out.println("Sorry you lost.");
break;
}
OK, so I'm not sure exactly what is supposed to do what but I will give it a try. It looks like you got a little confused.
For example:
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
In this code you seem to be printing to console a comparison of the variable bossOneHP and bossOneHP - (OP - bossOneBP), which I think is not what you intended as the statement would print true only if (OP-bossOneBP) was zero (basic algebra). What I suspected you intended:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP = bossOneHP - (OP - bossOneBP);
}else if(selection == 2){
This sets the variable bossOneHP to itself minus (OP minus bossOneBP). Note you can also do it like this:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP-= OP - bossOneBP;
}else if(selection == 2){
Which is faster. -= sets a value to itself minus the following value as opposed to = which just sets it to the new value. Also == does a comparison returning true if they are equal while = sets a variable to a new value.
Second issue:
if (bossHP == (0 || >0){
I am assuming you want to activate the if statement if bossHP is less than or equal to zero. The || statement is a boolean operator (It compares the two boolean inputs on either side, whether that be a variable or a comparison or a function, and returns a single boolean value of true if either input was true), and does not function like the word or. To compare two numbers (in this case the variable bossHP and zero), you use one of several operators. They are as follows:
== -returns true (which activates the if statement) if the numbers or objects (if they are the same instance, not if they contain equal values) on both sides are identical.
< -returns true if the left hand number is smaller than the right hand one (doesn't work on objects)
> -returns true if the right hand number is smaller
<= -returns true if the left hand number is smaller or equal to the right hand number
>= -returns true if the right hand number is smaller or equal to the left hand number
!= -returns true if the numbers or objects do not equal each other (effective opposite of the == token)
! -only takes one boolean on the right hand side and returns its opposite (this inverts the value essentially), if(!val) is equivalent and better to if(val == false)
The correct code would probably be something along the lines of:
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
also instead of doing the while(keepPlaying) thing you could also do while(true) and run a break; command when 3 is inputed

if statement string always prints

do{
System.out.println("Would you like to enter another number? (y/n)");
restart = console.next().charAt(0);
if (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'))
{
System.out.println("You entered something other than the letters (y) or (n).");
}
else if (restart=='n'||restart=='N')
{System.out.println("Goodbye.");}
}
while (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'));}
while (restart=='y'||restart=='Y');}}
I want the user to enter upper or lower case y or n and if its y then restart the program which worked fine before i started to add something to catch anything that wasnt a y or n. I want upper or lower case n to display goodbye and nothing happen and anything other than y or n to ask again to enter y or n until it gets the corect input and instead it always displays the you entered something other than... message and repeatedly asks if ud like to enter another number
Another alternative that you may prefer is to write
while("YyNn".indexOf(restart) == -1)
which means "loop again if restart is not found in "YyNn" ".
Replace || with && when you use it with ! - otherwise you have a condition that's always true. restart is ALWAYS either not Y or not N, and sometimes both.
This
if (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'))
is the same as
if ((restart!='y')||(restart!='n')||(restart!='N')||(restart!='Y'))
So you probably want
if(!((restart=='y')||(restart=='n')||(restart=='N')||(restart=='Y')))
and this is the same as
if ((restart!='y')&&(restart!='n')&&(restart!='N')&&(restart!='Y'))
You can also make this if statement better by converting the value to upper or lower case letters and compare that. Then you would only have to write code for 'N' and 'Y' or 'n' and 'y'.
You should use && instead of || in first IF and While condition check.
do {
System.out.println("Would you like to enter another number? (y/n)");
restart = console.next().charAt(0);
if ((restart != 'y') && (restart != 'n') && (restart != 'N') && (restart != 'Y'))
{
System.out.println("You entered something other than the letters (y) or (n).");
}
else if (restart == 'n' || restart == 'N')
{
System.out.println("Goodbye.");
}
}
while ((restart != 'y') && (restart != 'n') && (restart != 'N') && (restart != 'Y'));
Well, first of all you do not need to create an option for capital and lowercase letters. Use .equalsIgnoreCase(). Use && instead of or because you are saying if they put yes or no it will restart.

Printing a statement only once in a while loop

This is probably very simple, however I have completely blanked and would appreciate some pointers. I'm creating a small game we have been assigned where we select numbers and are then provided a target number to try and reach using the numbers we selected. Inside my while loop once my condition hits 6 it asks the user to generate the target number, however once they do it prints the same string again "Generate the final string" how do I print this only once?
Here is the code if it will help.
while (lettersSelected == false) {
if (finalNum.size() == 6) {
System.out.println("3. Press 3 to generate target number!");
} // Only want to print this part once so it does not appear again.
Scanner input = new Scanner(System.in);
choice = input.nextInt();
switch (choice) {
case 1:
if (finalNum.size() != 6) {
largeNum = large.get(r.nextInt(large.size()));
finalNum.add(largeNum);
largeCount++;
System.out.println("Numbers board: " + finalNum + "\n");
}
break;
It can be done very easily.
boolean isItPrinted = false;
while (lettersSelected == false) {
if ((finalNum.size() == 6) && (isItPrinted == false)) {
System.out.println("3. Press 3 to generate target number!");
isItPrinted = true;
}
The condition if (finalNum.size() == 6) is satisfied first and so the string is printed. However, during the next iteration of the while loop, the size of finalNum has not changed as the contrary of the condition is checked in the case 1 of the switch and the size is not changed anywhere between these two statements.
You can add a flag variable and set it to true, add a check for that variable in the if contidion and if the if-clause is entered, set the variable to false:
boolean flag = true;
while (lettersSelected == false) {
if (finalNum.size() == 6 && flag) {
System.out.println("3. Press 3 to generate target number!");
flag = false;
}
// ...
}

Categories