Loop until valid input is reached [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}

You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator

That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {

You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.

You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)

You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).

Related

java equalsIgnoreCase() in a do-while loop always returning false; [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 7 years ago.
I'm simply trying to determine if the user has entered a YES or NO value (disregarding caps though, hence equalsIgnoreCase()). However, regardless of me entering YES or NO, the do-while doesn't break E.G.
public int addInformation() {
final int YES = 1;
final int NO = 0;
String userDecision = "";
try(Scanner scanner = new Scanner(System.in)) {
System.out.println("Add Information Now? [YES/NO]");
do {
System.out.println("Please Enter YES or NO ");
userDecision = scanner.nextLine();
} while(!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"));
}
if(userDecision.equalsIgnoreCase("yes")) {
return YES;
}
return NO;
}
I'm looking for the behavior of "while the input value is not equal to 'yes' OR 'no', ask for the data again". However my code suggests "disregard whatever is typed, let's just keep looping for fun..." Where did I go wrong, Stack? thanks
This condition
while (!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"))
is always true. Any string must be EITHER not equal to "yes" OR not equal to "no".
If you mean to check that the string is not equal to either, you mean this:
while (!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"))
Your condition is incorrect. You want to end the loop if either condition is false (so you need an and). Something like,
while(!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"));

Beginner looping issue- while ... do

What the program does: Reads two values from input, asks user whether to add, subtract, or find the product. If user enters one of the three options, it calculates, otherwise the program will loop back to the beginning. The program should STOP after calculation if the user enters one of the three options.
I'm not sure why it keeps on looping. How do I make the script loop only when the user types in a string other than "sum", "difference", or "product"? Also, how can I make the code simpler? Is there any way to loop the program without using do ... while?
import java.util.Scanner;
import java.util.Random;
public class simp_calculator
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double a, b;
String response;
boolean noresponse;
do
{
System.out.println ("Please enter first number.");
a = scan.nextDouble();
System.out.println ("Please enter second number.");
b = scan.nextDouble();
System.out.println ("Would you like to find the sum, difference, product?");
response = scan.next();
if (response.equalsIgnoreCase ("sum"))
{
System.out.println (a + b);
}
if (response.equalsIgnoreCase ("difference"))
{
System.out.println (a - b);
}
if (response.equalsIgnoreCase ("product"))
{
System.out.println (a * b);
}
else
{
noresponse = true;
System.out.println ("Starting again...");
}
}
while (noresponse = true);
}
}
You are using the assignment operator, =, so noresponse will always be true. The result of the assignment expression is thus true.
You want to check if it is true, so use the comparison operator ==:
while (noresponse == true);
or, because it's already a boolean:
while (noresponse);
Also, you may be getting a compiler error that noresponse may not have been initialized. You will need to make sure that it's initialized in all cases, and that something sets it to false so the loop will eventually end.
change while (noresponse = true); to while (noresponse == true);.
= is an assignment operation - where as == comparison.
Two errors:
The else applies only to the last if; so for any value, other that "product", noresponse becomes true and the loop goes on. Replace all your ifs from the second on with else ifs.
noresponse should be given the value false at the beginning of the loop.
There are 2 issues:
Currently you are looping while noreponse equals true. So to exit that loop, you need to setnoresponse to false when a particular condition is met :) I could give you the answer, but you should be able to figure it out with the info I've given you. (hint: at some point you need to set noresonse to false).
Also, you are setting noresponse to equal, rather than comparing it. You need to use == to compare.
So make while (noresponse = true); into while (noresponse == true);.
just change while (reponse = true) to while(reponse) and name the variable ..

Detecting Numbers in a String Variable (In Java) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So, normally for detecting user input, I use int and double variable types.
Example:
Scanner in = new Scanner(System.in);
int selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.nextInt();
if(selection == 1){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This technique usually works fine for me, but I noticed that if the user inputs a letter into the int variable, the game will crash because integers can't store letters. (right?) So I tried using a String variable in its place, like this:
Scanner in = new Scanner(System.in);
String selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.next();
if(selection == "1"){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This seemed to work at first, but as you can see, I have it set so that if the variable "selection" is equal to 1, that it will print "you are a soldier", yet this did not work, instead it printed out the "selection" variables value (1). Did I do something wrong or should I use a different type of variable?
you can use something la this :
try{
int type = Integer.parseInt(selection);
switch(type){
case 1:{
//do soldier stuff
}
case 2:{
// do knight stuff
}
default:{
//do other stuff
}
}
}catch(NumberFormatException exc ){
System.out.println(selection + "is not a number, try again!!!");
}
selection == "1"
Compare strings with String#equals.
"1".equals(selection)
There are lots of ways to do this. A quick point I'd like to make is if you're comparing strings you should use:
var.equals("string");
Since you're only taking one character you could use a character in which case the correct syntax would be:
var == '1'
If you want to be fancy you can do a try catch around your read statement and just read in an string and parse it to an integer, but that is a bit more advanced.
change selection == "1" to "1".equals(selection)
use .equals() for comparing the string "1" and selection and read this A simple explanation would be
x == y returns true only when both x and y refer to same object which is not in your case. equals check if contents are equal meaning if contents of memory location that x and y are referring to are equal or not.

Input String check [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing an ATM program and when the user inputs one of the string values the program should check it an do a method accordingly. The problem code is here:
System.out.println("PRESS");
System.out.println("(D)eposit");
System.out.println("(W)ithdraw");
System.out.println("(C)heck Account Balance");
System.out.println("(Q)uit");
System.out.println("Enter Choice: ");
String choice = scanner.nextLine();
scanner.nextLine();
if(choice == "D"){
currentCustomer.deposit();
}
else if(choice == "W"){
currentCustomer.withdraw();
}
else if(choice == "C"){
currentCustomer.checkBalance();
}
else if(choice == "Q"){
currentCustomer.quit();
}
else{
System.out.println("Invalid choice please reenter: ");
}
If a user enters in "D" the program skips to the else statement. I know when using .nextLine you have to use two because of the return character but I'm not sure if that is true with this case. Either way if I have the extra .nextLine statement or not it still skips ahead. Any help would be much appreciated!
In Java we compare strings with String#equals.
I'll not write the difference between equals and ==, google for more information. You'll get around 100 results.
You would be better off using if(choice.equals("D")) in your code. You can't compare strings with == because you are just checking the memory and not the actual contents.
Instead of using String in comparison part:
else if(choice == "C"){
currentCustomer.checkBalance();
}
you could use char comparison instead
else if(choice[0] == 'C'){
currentCustomer.checkBalance();
}
You shouldn't be using the == operator to compare strings, use the String equals method instead. The operator checks to see if both strings are stored at the same location in memory while the method checks if they have the same content.
If you're using Java 7, you might want to switch out that if-elseif-then block with a switch statement. Java 7 introduced the ability to use strings in switch statements.

Do-while loop won't escape - Java

Does a do-while loop check a value before or after it has been incremented? I can't seem to make this do-while loop escape, and can't determine if that is the mistake I am making. The point of this loop is to take input from the user and when they hit 'X', I want the loop to end. Am I using the wrong type of loop, or perhaps an incorrect statement?
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(coefficient[i] != "X");
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Specifically in your case, I'd change
} while(coefficient[i] != "X");
to something like:
} while(!"X".equalsIgnoreCase(coefficient[i]));
And you've got another problem in your code in that you want to test the user input which you place into coefficient[i], but then you promptly increment the i variable such that coefficient[i] no longer refers to the input.
So perhaps the test should instead be:
} while(!"X".equalsIgnoreCase(coefficient[i - 1]));
You're incrementing i between coefficient[i] = keyboard.nextLine(); and while(coefficient[i] != "X");, so in the while check coefficient[i] is null, also use .equals to compare strings.
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(!coefficient[i-1].equals("X"));
There is two problems here. First you shouldn't compare Strings using logical operators. Use .equals instead.
For example:
coefficient[i].equals("X");
Secondly you are incrementing your array index counter before you check the while condition. So you actually need to subtract one from it to check if the most recently entered String was X.
See if using this will get it working:
coefficient[i-1].equals("X");

Categories