This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
The or statement in the first line of my if statement is not working as i would expect it to, any suggestions?
if(answer == "deposit" || "Deposit"){
System.out.println("How much would you like to deposit?");
final int deposit = console.readInt();
account.deposit(deposit);
System.out.println( "This leaves you with $" + formatter.format(account.getBalance()) + " in your account");
}else if(answer == "Check Balance"){
System.out.println( "You have $" + formatter.format(account.getBalance()) + " in your account");
}else if(answer == "Withdraw"){
System.out.println("How much would you like to take out?");
final int with = console.readInt();
account.withdraw(with);
System.out.println( "This leaves you with $" + formatter.format(account.getBalance()) + " in your account");
}else{
System.out.println("You didn't enter a correct term, please try again.");
}
First, logical-OR conditions don't work this way in Java like they do in English. You must write it out explicitly. Second, don't use == to compare String values. Use equals() for all String value comparisons.
if ("deposit".equals(answer) || "Deposit".equals(answer))
Or you can use equalsIgnoreCase().
if ("deposit".equalsIgnoreCase(answer))
Use the method 'equals' for string comparison. E.g. answer.equals("deposit").
Use if (answer.equals("deposit") || answer.equals("Deposit")) {
and }else if(answer.equals("Check Balance")){
Testing if strings are equal in Java should not be done with ==, but with:
if ( answer.equals("Check Balance") )
With == you compare pointers of String objects, but answer and "Check Balance" are different object - second one is created during test so even if they have equal value, they are not identical. equals check only object's content.
For String you need to use String.equals method
if("deposit".equals(answer)){
Change
if(answer == "deposit" || "Deposit"){
as
if(answer.equalsIgnoreCase("deposit")){
or
if (answer.equals("deposit") || answer.equals("Deposit")) {
Reason
equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am relatively new to coding in general and have run into an issue, I've looked everywhere for help but I cant find this issue. It would be greatly appreciated if someone could tell me why the string "s" doesn't ever equal the string "temp" even if I type the correct number in.
String s = null;
do{
s = (String) JOptionPane.showInputDialog(null, "Select a card to check for (Jacks = 11, Queens = 12, Kings = 13)", "Player's Turn", JOptionPane.PLAIN_MESSAGE, null, null, "Pick a card");
System.out.println(s);
for(int x = 0; x < PlayerCards.size(); x++){
String temp = PlayerCards.get(x).getFace();
if(s == temp){
playerhas = true;
}
}
if(s == null || playerhas != true){
JOptionPane.showMessageDialog(null, "Please pick a card you have.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}while(s == null || playerhas != true);
Strings work like objects in Java.
If you do stringA == stringB this will always return false since stringA and stringB are different objects.
Comparing strings needs to be done using stringA.equals(stringB) and this should return true (if the values match).
Chris 7 you're right that strings are objects but new compilers do some optimizations on those strings and it could happen that stringA == stringB are equal but it's not promised. So you should always use the string comparison functions (String.equals or String.equalsIgnoreCase).
By the way you can optimize your code. Use functions that implement only one feature and not more... e.g. externalize your function that checks if one has the card or not:
boolean playerHas(String s) { for (PlayerCard card : playerCards) { ... } return false; }
The
==
operator compares objects, while the
.equals
function compares object values.
String foo = "loremipsum";
String bar = "loremipsum";
System.out.println(foo == bar);
System.out.println(foo.equals(bar));
this ==compare bits, it works with primitive variable because when you declare a primitive variable it saves its value in bits, but when you declare a reference variable it only works if two reference are the same.
See this example:
String object1 = new String("hola");
String object2 = object1;
System.out.print(object1==object2);
This will return true because object2 have the same bits that point to the same object on heap, because they were copied when i said:object2 = object1
So if you want to compare objects by value instead by reference you have to use: equals() method.
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
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am using Java and have been trying to split my string input into 3 parts. For example, my input will be "AND 1 1", and I am expecting it to go into my if-loop where the condition is parts[0] == "AND". But this is not the case, and I am not sure why.
My code is listed below
Scanner stringInput = new Scanner(System.in);
String input = stringInput.next();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
In Java you can not be sure that the string is the object you think it is. For this reason, you should not use == to compare objects, but use the equals function.
if (parts[0] == "AND")
should be
if (parts[0].equals("AND"))
Strings are immutable, so the functions will always return new strings, when they have to do something on them. For this reason, using == will only work in some particular cases, but never when you process them.
You are using stringInput.next() which will not read spaces. So that is the problem.
Use stringInput.nextLine() instead of stringInput.next()
String input=stringInput.nextLine(); is correct when you are working with text that contains space.
Here is the edited code.
Scanner stringInput = new Scanner(System.in);
String input = stringInput.nextLine();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
You probably might have got an ArrayIndexOutOfBoundsException
You are using the String.split() method in correct way. The parts[0] also contains the desired "AND" after using the method.
But the problem is you are checking equality of two strings using "==" instead of equals method. When you use == then it checks whether they are same reference of string while the equals method check the values of the string.
So your checking should be something like this
if (parts[0].equals("AND"))
Use
parts[0].equals("AND") to check equality of `String`
Just to complete the Devolus answers (I can't put comments in comments yet U_U)
== compares the references, it means that is only true if two variables are pointing to the same object
e.g.
Object a = new Car()
Object b = a
Object c = new Car()
(a == b) //true
(a == c) //false
a.equals(b) //true
a.equals(c) //true
Try this piece of code:
if (parts[0].toString().equals("AND")){
if (parts[1].equals(parts[2]) && parts[1].equals("1"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}else {
if (parts[1].equals("1") || parts[2].equals("0"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}
There are several issues:
as JavaTechnical pointed out, you should use stringInput.nextLine() vs stringInput.next()
as everyone pointed out, use .equals() vs ==, here's a thread explaining why: Java String.equals versus ==
test against a known vs an unknown, reorder your test like so "AND".equals(part[0]) should shield you from null pointer
Try using .substring(), for example:
String a = "AND 1 1"
b = a.substring(1,3)
c = a.substring(4,5)
System.out.println(b)
System.out.println(c)
Would print "AND" then "1"
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
So, I have a question regarding the testing operators and strings. I'm trying to write a program that will take in user input of either "boy" or "girl". When the user inputs "boy", the output should be "You are a boy." When the user inputs "girl", the output should be "You are a girl."
However, when I compile and run the program, no matter what I input, the output is always "You are a girl."
Is this because the strings have no actual value like integers and therefore, testing operators cannot be used to compare them?
Also, is there anything like the assert function from python in java?
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
if (text == "boy"){
System.out.println("You are a boy.");
}
else{
System.out.println("You are a girl.");
}
}
}
Thanks a lot~
Use
text.equals("boy")
instead of
if (text == "boy")
The reason is, In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
But the better option is to use equalsIgnoreCase, the reason is that user may enter boy or BOY or Boy or any other combination. equalsIgnoreCase method just ignores the case and compares two strings.
text.equalsIgnoreCase("boy")
Side note. Input other than Boy will get you to print Girl. Put one more extra if condition. Also before going for comparision, being on safer side trim the string for blank spaces.
Use
text.equals("boy")
or
text.equalIgnoreCase("boy")
if its not case sensitive.
instead of
if (text == "boy")
Your coade will be something like this
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
text = text.trim();
if (text.equalIgnoreCase("Boy")){
System.out.println("You are a boy.");
}
else if(text.equalIgnoreCase("Girl")){
System.out.println("You are a girl.");
} else {
System.out.println("Invalid Gender");
}
}
}
use text.equalsIgnoreCase("boy")
if you think about case also it will check content of string is same.
== is used to check for object equality.
text.equals("boy") is ok if you not consider about case.
Please use equals method for string like : if (text.equals("boy")){
== is not for string contents equality check in java
== tests if object identity is the same. When you have two string objects containing the same value this object identity won't be equal. Use the equals function to test for logical equivalence.
Your if else is wrong. Use only if here. Otherwise,
If I entered "some text", the output will be "You are a girl"
Like this
if (text.equalsIgnoreCase("boy")) {
System.out.println("You are a boy.");
}
else if (text.equalsIgnoreCase("girl")) {
System.out.println("You are a girl.");
} else {
System.out.println("You are neither a boy nor a girl");
}
It would be best to use the .equals method instead of == boy
For your other question regarding assert:
Java has an assert function. This is the sample code.
assert(x <= 50): "Not Accepted";
This code checks if integer x is greater than 50. You will see the output at the console.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public void play () {
int anInteger;
//guess return code
int code;
while (true) {
String input=null;
input = JOptionPane.showInputDialog("Please enter an integer");
if (input == "-1") {
//JOptionPane.showMessageDialog(null, input);
System.exit(0);
break;
} else {
if (input==null) {
System.exit(0);
} else if (input.isEmpty()) {
continue;
} else {
anInteger = Integer.parseInt(input);
code = this.oneGuess (anInteger);
//JOptionPane.showMessageDialog(null, anInteger);
}
}
}
}
I want, if the user enter -1, show the program will not prompt the message box any more. Above is the code I have come up with, so far. Why it doesn't work?
String comparisons does NOT work with "==" operator, use "String.equals(Object)" function
input.equals("-1");
Better way would be
"-1".equals(input);
as it also takes care of null input
You are comparing strings, which are objects, with the == operator, which checks whether two object references refer to the same object instance. Instead you should use the equals method for comparing them.
There is a difference between comparing with == and equals. The first compares pointers, the latter contents. That is probably your issue.
You compare Strings with ==, which creates a problem. You can have many different String-Objects which all show "-1". The == tests, if you have exactly the same object on the left and right side. You want to know, if the objects on the left and right sie have an equal content.
Better try
input.equalsIgnoreCase("-1");
EDIT: To answer the comment: input.equalsIgnoreCase("-1") is the same as input.equals("-1") in the case of "-1" as there are no uppercase/lowercase letters in "-1". However, I prefer equalsIgnoreCase in the case of Strings, because it is defined on String, rather than on Object. Still, as the equals-definition is overridden for the String class, it works too in this example and "ignoreCase" is not needed.