How to reprompt user for a valid string input? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am creating a program that simulates Rock, Paper, Scissors, and I need the user to input either "Rock","Paper", or "Scissors". My Code is:
Scanner input = new Scanner(System.in);
String userIn = null;
while ((userIn != "Rock") || (userIn != "Paper") || (userIn != "Scissors")) {
System.out.println("Please Type either: Rock, Paper or Scissors");
userIn = input.next();
}
I created a scanner for the input and set the initial input to null. When the program runs, since the input is not either "Rock","Paper", or "Scissors", it will prompt the user to enter one of those three, the problem is even when I enter "Rock","Paper", or "Scissors" correctly, it still reprompts me to "Please Type either: Rock, Paper or Scissors".
what am I doing wrong?

For string comparisons use
userIn.equals("yourString") function rather than != comparisons.

You should try using .equals() or better .equalsIgnoreCase() if you are not bothered about the case of the input string. That might help.

equal or equalsIgnoreCase uses the content of object to make compare,but != do the comparison with the reference address
so the code should be
while ((userIn.equalsIgnoreCase("Rocker")) || (userIn.equalsIgnoreCase("Paper") || (userIn.equalsIgnoreCase("Scissors"))

Update your program like this,
Scanner input = new Scanner(System.in);
String userIn = "";
while (!(userIn.equals("Rock") || userIn.equals("Paper")|| userIn.equals("Scissors"))) {
System.out.println("Please Type either: Rock, Paper or Scissors");
userIn = input.next();
}
firstly, if you are doing
String userIn = null; //instead String userIn = " ";
we can't check
userIn.equals("Rock"); // i.e. null.equals("Rock");
compiler will through a null pointer exception. So, edit your program as above and will work properly.

Related

How to return a value from a do while loop

I am trying to create a rock, paper, scissors game that requires a valid input from the user before continuing. How I was trying to tackle this was by making a do while loop and an if else statement inside to verify the input. If it is anything other than the choices given, then the condition stays false and the program loops. However I was trying to figure out how to return the correct value that the user inputs which gets stored in UserChoice so I can access the variable outside of the loop and continue on with the program.
Here is my code:
do{
System.out.println("Enter in rock, paper or scissors:");
Scanner user = new Scanner(System.in);
String UserChoice = user.nextLine();
if(!UserChoice.equals("rock") && (!UserChoice.equals("paper")) && (!UserChoice.equals("scissors"))){
System.out.println("You must enter either rock, paper or scissors. Try again: ");
}else{
isRight = true;
}
}while(isRight==false);
Initialize UserChoice before the do while.
String UserChoice = "";
do
....
while ();
System.out.println(UserChoice);
Next to declaring the variable outside of the loop (as I suggested in the comments earlier) a few remarks about your code:
System.out.println("Enter in rock, paper or scissors:");
Scanner user = new Scanner(System.in);
String userChoice = user.nextLine(); //stick to naming conventions, it makes your code easier to read
while(!userChoice.equals("rock") && (!userChoice.equals("paper")) && (!userChoice.equals("scissors"))){
System.out.println("You must enter either rock, paper or scissors. Try again: ");
System.out.println("Enter in rock, paper or scissors:");
userChoice = user.nextLine(); //stick to naming
}
There is no need at all to loop that entire block of code each time. All that needs to be repeated, is the error message and reading new value for userChoice, and that only if the original entry was invalid.
In your code, for instance, you are creating a new instance of Scanner each time you loop, while you could just reuse the existing one.
Just move the variable declaration out of the loop, to make it available out of the scope of the do-while block, just like:
String userChoice = null;
do{
System.out.println("Enter in rock, paper or scissors:");
Scanner user = new Scanner(System.in);
userChoice = user.nextLine();
if(!"rock".equals(userChoice) && (!"paper".equals(userChoice)) && (!"scissors".equals(userChoice))){
System.out.println("You must enter either rock, paper or scissors. Try again: ");
}else{
isRight = true;
}
}while(isRight==false);
//here you can still use it
System.out.println(userChoice);
You can read about variable scopes for example here.
And just some remarks. It's preffered to use "rock".equals(userChoice) notation while calling equals, in order to prevent NullPointerException if your userChoice object will be NULL, for any reason. Furthermore, you can move this line Scanner user = new Scanner(System.in); out of the loop. No reason to create new instance of the scanner on every iteration. And the last one, while condition isRight==false could be substituted with !isRight, no need to compare it to something, since the variable is boolean itself.

Stuck in a while loop trying to get the user to input certain words? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm making a simple rock, paper, scissors program. For some reason this while loop keeps looping even if the user enters one of the correct terms. Can someone explain why this is happening?
public static String userChoice(){
String userChoice = "";
while(userChoice != "rock" && userChoice != "paper" && userChoice != "scissors"){
userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
JOptionPane.showMessageDialog(null, "Invalid input!");
}
return userChoice;
}
you cannot compare String with the standard comparators, you want to use someString.equalsIgnoreCase(someOtherString)
Edit:
You can in certain (rare) situations use standard comparators, however this is not one of them.

Java: while loop doesn't return [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
New to Java, taking college course.
I am writing a program that asks users for their internet package so it can calculate their bill. Here's the snippet where I ask for their package, and have to confirm that they have answered either A, B, or C.
For some reason, it enters the while loop even if I enter "a"..
//Create Keyboard scanner
Scanner keyboard = new Scanner(System.in);
//Get user package
String servicePackage;
System.out.println("Enter your internet package: A, B, or C");
servicePackage = keyboard.nextLine();
servicePackage = servicePackage.toUpperCase();
System.out.println(servicePackage);//This line is for debugging
//Validate User Package Input
while (servicePackage != "A" && servicePackage != "B" && servicePackage != "C"){
System.out.println("Please enter a valid internet package (A, B or C)");
servicePackage = keyboard.nextLine();
servicePackage = servicePackage.toUpperCase();
System.out.println(servicePackage);//for debugging
}
System.out.println(servicePackage);//for debugging
Not sure if it's relevant, but I am using jGrasp.
Any help is appreciated!
"string" (declared) == "string" return false. You should use equals ("string".equals("string") return true) or equalsIgnoreCase (for example: "STRING".equalsIgnoreCase("string") return also true)

I can't get out of this while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the first section of my main method, where I prompt the users to input as many phrases as they want, and the input gets saved in an ArrayList. I coded this so that the program would stop asking for more input if the user puts 'q', but for some reason, when I run this, even if I input q, it doesn't exit the loop. It just keeps on asking for more inputs. I'm assuming I made a mistake in the while loop, but I'm not entirely sure what.
I'm really new to Java so I may have made a blatant mistake but I'm not sure..
public static void main(String [] args)
{
//vars
String userInput;
int quitter = 0;
//arraylist
ArrayList<RecursivePalindrome> a = new ArrayList<RecursivePalindrome>();
//scanner
Scanner in = new Scanner(System.in);
//user input
System.out.println("\t Palindrome Checker");
System.out.print("Input phrase one at a time (press 'q' to quit): ");
while(quitter == 0)
{
userInput = in.next();
if(userInput == "q" )
{
quitter++;
}
a.add(new RecursivePalindrome( userInput));
System.out.print("Input phrase one at a time (press 'q' to quit): ");
}
System.out.println();
Comparison of strings
use .equals
if(userInput.equals("q"))
{
quitter++;
}
Compare the String with equals() and put break it will exit the while loop
if(userInput.equals("q" ))
{
quitter++;
break;
}

The if statement is not properly executing after user inputs which if-statement they want to input [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 9 years ago.
package temperatureconversion;
import java.util.Scanner;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter Conversion type: Press C for Celsius to Fahrenheit or press F For Fahrenheit to Celsius.");
String Vctype = keyboard.next();
if (Vctype == "f" || Vctype == "F"){
System.out.println("Please enter fahrenheit");
double Vfahrenheit = keyboard.nextInt();
Vfahrenheit = (Vfahrenheit)*(9/5)+(32);
System.out.println(Vfahrenheit);
}
if (Vctype == "c" || Vctype == "C"){
System.out.println("Please enter celcius");
double Vcelcius = keyboard.nextInt();
Vcelcius = (Vcelcius - 32)*(5/9);
System.out.println(Vcelcius) ;
}
}
}
Hello guys I was wondering if anyone could help me with the above code. Basically in the output console in netbeans the program just seems to end after I hit C or F, but instead it should ask for a number then allow a number input, then calculate and finally display the calculation. It doesn't seem to be executing the if statements Where am I going wrong?
You are comparing String with ==. So it doesnt work, you have to use this :
if (Vctype.toLowerCase().equals("f"))
Note also, that using a "toLowerCase" makes the whole string lowercase, so you dont have to have two options for "F" and "f".
If you want, you can use "compareTo"
if (Vctype.toLowerCase().compareTo("f") == 0)

Categories

Resources