This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm currently working on a financial planning app for class but I cant get a loop with a condition inside it to work. It just keeps looping despite the condition - it's almost as if the condition is being ignored completely.
Here's my code - please help!
while (true){
Scanner scanVar = new Scanner(System.in);
System.out.println("\nEnter expenditure item: ");
String myString = scanVar.nextLine();
Scanner scanVar2 = new Scanner(System.in);
System.out.println("\nEnter expenditure value: ");
double myDouble = scanVar2.nextDouble();
expenditureMap.put(myString, myDouble);
Scanner scanVar3 = new Scanner(System.in);
System.out.println("\nAnother item? ");
String myString2 = scanVar3.nextLine();
if (myString2 == "yes") {
continue;
}
else {
break;
}
}
Many thanks,
Dylan
You really want to be using mystring2.equals("yes") (or even better, "yes".equals(mystring2) )
The == operator on objects tests for them being the identical instance, not the same string values....
String a = new String("yes");
String b = new String("yes");
a == b => false
a.equals(b) => true
If you are using the == operater it is comparing if the object references match. You should use the equals operator
if (myString2.equals("yes"))
change the condition as follows and then try:
if (myString2.equals("yes")) {
You shall use equals ... check this post
How do I compare strings in Java?
reference comparison means checking if both objects have the same address in memoery
value comparison means checking the value inside the objects
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String play = "y";
System.out.print("Enter something: ");
play = scan.next();
System.out.println(play);
if (play == "Y" || play == "y")
{
System.out.println("If test works!!");
}
System.out.println("Did it work???");
}
}
I assume this has something to do with when I press enter, it's storing that as well. I tried changing String play to a char, but then I get errors from Scanner saying it can't change a String to a char.
You should atmost avoid using “==“ when comparing objects especially strings. “==“ checks for object references. Change the comparison to use .equals method and it should work
if(play.equals(“Y”) || play.equals(“y”))
in case if “play” can be null, the below snippet is more safe.
if(“Y”.equals(play) || y.equals(play))
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I'm a total beginner at Java and am struggling with making a simple card game where you choose between values "red" and "black". Can anyone see what's wrong?
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
if (guess == s)
System.out.println("Correct");
else
System.out.println("Wrong");
} while (guess != s);
In Java Strings are an object, when comparing Objects:
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically
"equal").
This is further explained in How do I compare strings in Java?
On the other hand, char is a primitive data type and on primitive types == tests for value equality. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Edit - Regarding case:
In Java you have the method "equalsIgnoreCase" to compare two Strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and it represents an equivalent String ignoring case, else false.
So, you've got a couple of problems here:
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
//The problem is that you're using reference comparison, but that's not the only issue you 'will have', you're only checking raw input vs upper case 'R'
//and 'B' so you 'need' (you can handle this with lower case or alternative, too) to change this to `.toUppercase()`.
if (guess == s)
System.out.println("Correct");
else
System.out.println("Wrong");
//The same problem is happening here:
} while (guess != s);
New code:
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
if (guess.toUpperCase().equals(s))
System.out.println("Correct");
else
System.out.println("Wrong");
} while (!guess.toUpperCase().equals(s));}
When you use ==, you're comparing references.
To compare text (string type), you should use .equals().
You should also make sure that the case upper/lower is catered for to prevent errors, as r is not equal to R.
Basically, don't use == for strings, that's only good for primitive data types or basically anything that isn't an object. Because that points to the reference of the string and compares if they're equal (Basically testing if they're the same variable not the same string contents. In the case of strings you want to use .equals(), Usually I put a ToUpperCase() statement in there like so:
if(guess.toUpperCase().equals(s.toUpperCase()))
to get rid of case sensitivity because it just makes everyones lives easier but I know thats not a part of the question
tldr: Use .equals when comparing strings, otherwise it points to the objects of the string and not the contents.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
For a mini game in where the user tries to guess a name. But when I want to compare two text strings just to check if are the same it seems that doesn't work.
final String miName = "Jhon";
Scanner input = new Scanner(System.in);
System.out.println("Guess my name: ");
while (true) {
String attempt = input.next();
if(attempt == miName) {
System.out.println("Congrats!");
break;
} else {
System.out.println("Try it again!");
}
}
The output:
Guess my name::
Karl
Try it again!
jhon
Try it again!
Jhon
Try it again!
You need to use .equals in case of String.
== gives true only when both the object's address match (or in case of primitive types).
Object class inherently compares the address in the .equals method and you need to override the .equals method if in case you wish to write your own custom logic for equality of two objects.
Classes like String, Integer, etc. have their equals already overridden.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am not sure why but when I get a string from the user, I cannot compare it in an if statement but when I try to print it, it works fine.
Part of my code:
Scanner in = new Scanner(System.in);
while (true) {
String userInput;
int rowInput, colInput;
printBoard(board);
System.out.print("Move: ");
userInput = in.next();
// shift board right on a row
if (userInput == "r") {
System.out.print("row #: \r");
rowInput = in.nextInt();
moveRight(--rowInput, board);
}
Does anyone know why this isn't working as expected?
You an try this:
if (userInput.equals("r"))
== is used to compare the address and equals is used to compare contents.
I should be using equals instead of ==.
So it would lead to:
...
if (userInput.equals("r"))
...
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Noob Java question: Why won't this Do While loop accept the user input? When I use a different variation (such as int for the answer), it works. But when I look for a string, it never accepts the string and escapes the loop.
This works:
int value = 0;
do {
System.out.println("Enter a number: ");
value = scanner.nextInt();
}
while(value != 5);
System.out.println("Do while loop has ended.");
This doesn't work:
String pass;
String word = "word";
do {
System.out.println("Enter password: ");
pass = scanner.nextLine();
}
while(pass != word);
System.out.println("Password accepted.");
Thanks
Change this:
while(pass != word);
to this:
while(!pass.equals(word));
You were comparing the references when you used !=, not the actual content of the strings. Since they did not point to the same String, your loop would always exit on the first run.
"==" compares addresses in memory so if you enter the word which will be the same, the reference you have stored will point to different object.