If statement not recognizing user input [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
public static void getSolve(Scanner s) {
boolean validInput = false;
while(validInput == false) {
System.out.println("Would you like to try to solve the word? (yes or no)");
String input = s.nextLine();
if(input == "yes" || input == "Yes") {
validInput = true;
System.out.println("Enter your full guess: ");
String guess = s.nextLine();
if (guess == secretWord) {
System.out.println("You guessed the word!");
displayString = secretWord;
}
else {
System.out.println("Sorry, that is not the word");
NUM_LIVES --;
}
}
else if (input == "no" || input == "No") {
validInput = true;
}
else {
System.out.println("Sorry, that is not a valid input");
}
}
}
This is the code that I am using for a solve method for a java project for my class in which I am coding a hangman game. I am trying to add a feature that asks the user if they would like to try to solve the word and then checks to see if they got that guess correct. Right now what is happening is that no matter what the user puts in, even if it is "yes" or "no", the program thinks that it is an invalid input and asks the question again, putting the code into an infinite loop. I'm not quite sure how to fix this and I'm not sure what I am doing wrong. Any help is greatly appreciated!

Looks good to me except this one:
input == "yes" || input == "Yes"
should be
"yes".equalsIgnoreCase(input)
And others:
guess == secretWord -> guess.equals(secretWord)
input == "no" || input == "No" -> "no".equalsIgnoreCase(input)

You need to compare strings using .equals in java.
if(input.equals("yes") || input.equals("Yes"))
You can also use .equalsIgnoreCase() so you don't have to write all forms of the word yes.
.equals() is used to compare objects.

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')
...

Why doesn't my Scanner work with 2 different if statements?

New to Java here. I made the following simple code that asks the user to choose between option 1 or 2. If the selected option is 1, then it should print "You said hi", which it works well, also if selected option is 2, it should prints "you said goodbye" which it doesn't, Am I missing something here? Maybe the If statement is wrong?
the Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
if (input.nextInt() == 1) {
System.out.println("You said hi");
} else if (input.nextInt() == 2) {
System.out.println("you said goodbye");
}
}
Every time you call nextInt() it stops to wait for an int. Here you want to compare a single int from the user with one or two. Save the int you get from the user. Like,
int v = input.nextInt();
if (v == 1) {
System.out.println("You said hi");
} else if (v == 2) {
System.out.println("you said goodbye");
}
Every time you call nextInt() on your scanner, input is being consumed. So in your case, when the else if condition is checked, the next input is consumed, not the previous one compared. You need to cache your scanner's state:
int answer = input.nextInt();
if (answer == 1) {
System.out.println("You said hi");
} else if (answer == 2) {
System.out.println("you said goodbye")
}
For your specific case, converting to a switch statement would be another option, which evaluates its operand only once:
switch (input.nextInt()) {
case 1:
System.out.println("You said hi");
break;
case 2:
System.out.println("you said goodbye")
break;
}
Every call to input.nextInt() will wait for the new key from input(here it is the user input).
the input.nextInt() == 1 will wait for the user input.
If it is validates to true, the thread will successfully execute System.out.println("You said hi").
Else if it validates to false, it will execute the condition in the input.nextInt() ==2 where the thread will keep waiting for the next input from the user because of the input.nextInt().
If you wish to get input from user only once, execute input.nextInt() only once and store it in a variable and run cases against it. Like,
// input from user
int selection = input.getInt();
if (selection == 1) {
System.out.println("the user entered 1");
}
else if (selection == 2) {
System.out.println("the user entered 2");
}
Please get input first then check it. (Don't get input in condition statement).
Your edited code is as follows:
Added one line (int selectedOption = input.nextInt())
edit condition statement (selectedOption == 1 and selectedOption == 2)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
//Get input
int selectedOption = input.nextInt() ;
//Check
if (selectedOption == 1) {
System.out.println("You said hi");
} else if (selectedOption == 2) {
System.out.println("you said goodbye");
}
}

java (eclipse) code for rock paper scissors, choosing an input that is simple, and generating an output of rock paper or scissors

I need to create a program that asks the user for a string value and returns a string value of "rock" "paper" or "scissors" if the input was "r" "p" or "s" If the user typed in something different.
package loopsGamesProject;
import java.util.Scanner;
public class LoopsGamesProject_RockPaperScissors {
public static void main(String[] args) {
String in="-";
Scanner input= new Scanner(System.in);
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
while(in!="r"||in!="p"||in!="s") {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
}
}
input.close();
System.out.print(in);
}
}
}
The issue is, it will ask for a variable, but the terminate itself. I've tried adding an "out" variable. When I tried to do this using a do while loop, it kept asking for an input but never returned anything. I can't find the issue.
When you compare Strings in java, you need to use the .equals() method instead of the == function. This rule applies for all objects in java, String inclusive.
EG:
if (in.equals("r"))
//Rock!
You also need to replace the != and add a break statement to exit the loop. Something like this will do:
while (!(in.equals("r") || in.equals("p") || in.equals("s"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else
in = "Scissors";
break;
}
}
EDIT: The above prompts twice. This will fix it:
public static void main(String[] args) {
String in = "";
Scanner input = new Scanner(System.in);
while (!(in.equals("Rock") || in.equals("Paper") || in.equals("Scissors"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r")) {
in = "Rock";
}
if (in.equals("p")) {
in = "Paper";
}
if (in.equals("s")) {
in = "Scissors";
}
break;
}
}
input.close();
System.out.print(in);
}
As has been mentioned, you need to compare String equality using the String.equals(Object anObject) - alternatively you may use others methods (compareTo), but the == operator will not suffice (See here why).
On top of this, when you match the String you overwrite the String with the full word - in = 'r'; -> in = 'Rock';. But the condition you use to loop will only terminate when in is r, p or s specifically.
Further, you have some duplicated code there that could be reduced significantly. This is not a bug, but this can become very difficult to manage very quickly.
All things considered:
while (true) {
// Get the next input
in = input.next();
// Maps the word to the character
// If a word was not mapped, try again.
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else if (in.equals("s"))
in = "Scissors";
else
continue;
// Terminate the loop as you can infer a match was found.
break;
}

Check for a specific set of characters(of a password) in a string

I have to write a program which checks a password.
If the password entered by the user is 'bolt', it will display 'The password is valid'
Otherwise it will display 'The password is invalid'.
The program is working only for the if part but not for the else.
That is when I input bolt, it displays the correct message.
But when I enter something other than bolt, it does not display 'The password is invalid'.
I have been told to test for all four characters that is to use char.At.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your 4-character password:");
String password = input.next();
for (int i = 0; i < password.length(); i++) {
if (password.charAt(i) == 'B' || password.charAt(i) == 'b')
if (password.charAt(i + 1) == 'O'
|| password.charAt(i + 1) == 'o')
if (password.charAt(i + 2) == 'L'
|| password.charAt(i + 2) == 'l')
if (password.charAt(i + 3) == 'T'
|| password.charAt(i + 3) == 't') {
System.out.println("The password is valid");
}
else {
System.out.println("The password is invalid!");
}
}
}
It would be more readable to check using equalsIgnoreCase():
String password= input.next();
if(password.equalsIgnoreCase("bolt"){
System.out.println("The password is valid");
}
else{
System.out.println("The password is invalid!");
}
Why don't you just check for String equality directly?
String password= input.next();
if("bolt".equals(password))) {
System.out.println("Valid password");
} else {
System.out.println("InValid password");
}
Or use equalsIgnoreCase() if you'd also consider BOLT or Bolt valid.
If you need to implement this without equals you could use something like this:
if (password != null &&
password.length() == 4 &&
(password.charAt(0) == 'B' || password.charAt(0) == 'b') &&
...) {
System.out.println("Valid password");
} else {
System.out.println("InValid password");
}
For your updated question:
String password = input.next().toLowerCase();
String correctPassword = "bolt";
if (password.length() != correctPassword.length()) {
System.out.println("Not valid");
return;
}
for (int i = 0; i < correctPassword.length(); i++) {
if (password.charAt(i) != correctPassword.charAt(i)) {
System.out.println("Not valid");
return;
}
}
System.out.println("Valid");
In your code there are two problems,
1. Your for loop doesn't serve any purpose because you have checked the whole password in the first iteration itself. Your second iteration would cause IndexOutOfBoundsException.
You didnt see the invalid password message because, your else condition is applied only to the innermost if (which checks for the char "T" or "t").
So, if the provided password starts with "BOL" but last char is different like "BOLA" or "BOLB", then you would see the invalid message. But if the first three char fail, then it wont execute the else.
Hope this helps..
I'did use string.matches function which accepts regex as argument. (?i) helps to do a case-insensitive match.
if(string.matches("(?i)bolt"))
{
System.out.println("Valid password");
}
else {System.out.println("InValid password");}
What you are doing is not making much sense. You should probably use a character array an then check sequentially. Another small thing is that the else block is associated with the last if statement. Where it should be attached to the first if. This is one place where you need to use braces intelligently.

Why won't my Java code work? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I know this code is terribly written (first day of Java and programming), but I am writing a code in Java that will take an input from the user (the dice) and produce a random number from that dice. I have added a while loop to ask if the user would like to restart the program, but everytime I run it it tells me that it is an invalid input before I have inputted anything. Please help.
import java.util.Scanner;
import java.util.Random;
public class Java {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String restartChoice = "y";
while (restartChoice == "y" || restartChoice == "Y"){
int choice;
System.out.println("Please choose which dice you would like to roll. 4/6/12 ");
choice = input.nextInt();
while (choice != 4 && choice != 6 && choice != 12){
System.out.println("That is not a valid input, please try again... ");
choice = input.nextInt();
}
Random rand = new Random();
int value = rand.nextInt(choice) + 1;
System.out.print("You chose to roll the ");
System.out.print(choice);
System.out.print(" sided dice. The number is ");
System.out.println(value);
System.out.println("Would you like to restart? Y/N ");
restartChoice = input.nextLine();
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
}
}
}
Scanner#nextInt() does not consume newline characters resulting in the character being passed through to the loop
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
Add a nextLine statement after every nextLine statement to consume this newline character.
choice = input.nextInt();
input.nextLine();
Also the == operator compares Object references. Use String#equals:
while (restartChoice.equals("y") || restartChoice.equals("Y")) {
to protect against NullPointerException you can place the String literal first. Also equalsIgnoreCase can be used to give a shorter if statement expression:
while ("y".equalsIgnoreCase(restartChoice)) {
This change is required in for while statement expression.
Use String.equals(otherString)
Strings are objects, not primitives. You are currently comparing the addresses of your strings.

Categories

Resources