This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am trying to create a file system/file commander in java, and I want to make the following loop a quit system that triggers when I type dc.
public static void main(String[] args)
boolean x; x=true;
String dc; dc="dc";
while (x=true) {
System.out.println("_____________________");
System.out.println("local disk C:");
System.out.println("bin");
System.out.println("_____________________");
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd==dc) {
break;
}
}
So this is the code for the file commander, it's part of a game so ltstcm is a scanner, and lstcmd is a string you use to input commands for the game (Can't re-use it, I kept adding d's.), like I said before I want to leave this loop when I write dc, I made an if that checked lstcmdddd, I tried with checkingif (lstcmdddd=="dc") and that didn't work. I suspected that changing the value of the boolean x wouldn't work after discovering 'break', that failed. I then tried defining the string dc which contained "dc", and that didn't work either. I searched Stack Overflow about quitting loops, quitting loops failing, and changing values after defining a variable correctly. Nothing relevant to my problem, nothing I could salvage to solve the problem. (I AM NOT ASKING ABOUT COMPARISON!)
You cannot use the == comparison for strings, you have to use .equals, ie: lstcmdddd.equals("dc").
In Java, Strings are objects, so you cannot compare them using the double equal operator. As you are doing that however, your conditional will always return false and the break statement will never execute.
You should rather use .equals than ==. == is used to compare a single char or number, while .equals is used to compare strings.
[...]
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd.equals(dc)) {
[...]
Use ltstcmdddd.equals(dc) instead of ltstcmdddd==dc
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal
Related
This question already has answers here:
Best way to format multiple 'or' conditions in an if statement
(8 answers)
Closed 1 year ago.
Let's say I am trying to assign variable hit to true or false depending on whether user input is equal to either "yes" or "y" (I have the .toLowerCase() handled). Is there a way I can use .equals in a way that compares one string to two other strings all in the same line? I did a bit of searching, but I did not find anything, possibly because of the wording of a question like this.
My line of code:
boolean hit = kb.next().toLowerCase.equals("y"); // Change something to see if kb.next() also equals "yes"
So, to repeat, the code should see whether string a equals string b or string c.
If it is impossible to do this on one line, then just say so in the comments or provide an alternative that is hopefully concise.
You can't use equals to compare with two strings unless you call it twice, like this:
String input = kb.next().toLowerCase();
boolean hit = input.equals("y") || input.equals("yes");
You could alternatively use a regex:
boolean hit = input.matches("y(es)?");
Or if you don't mind matching the string "ye" as well as "y" and "yes", you could use startsWith:
boolean hit = "yes".startsWith(input);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I want to make a program that keeps getting string input and only stops when "." is entered, any ideas how to make it?
I understand that I need to make a string array, but what's the length I'm gonna give it if I dont know how many strings the user will enter?
This is my first time to use this website, so excuse me for any mistakes.
Thank you.
Edit:
Here's a code that is confusing me. I keep entering dots but the for loop never breaks. Also the length is currently 10, how can I make it unlimited until the input is a dot?
Scanner s=new Scanner(System.in);
String[] x = new String[10];
for(int i=0;i<10;i++)
{
x[i]=s.next();
if(x[i]==".")
break;
}
Scanner s=new Scanner(System.in);
ArrayList<String> inputs = new ArrayList<>();
while (true) {
inputs.add(s.next());
if(inputs.get(inputs.size().equals("."))
break;
}
Remember to import ArrayList. Check the documentation for more information about ArrayList.
In java == is an operator used for comparing references. your new String won't have the same reference as "." which will be created at compilation time.
equals() method is used for comparing if the objects equal. In case of String it compares char by char to see if they are all the same. If yes, it returns true. False otherwise.
Remember to always #Override the public boolean equals() in your class. You have to decide what it means that to object of a certain class are equal and implement it. it'll be useful if you read this topic. It's widely described there.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I understand and know why you typically have to use == to compare strings in java, but for some reason I am able to do it in Eclipse. My code is
Code:
public class Test{
public static void main(String [] args){
String str1 = "string";
if(str1 == "string"){
System.out.println("wtf");
}
}
}
Why does this print "wtf" yet using javac from command line does not?
Eclipse allows you to compare references because it is a legitimate comparison. Just probably not the one you really want.
Because of String interning it will sometimes appear to work, but you should not rely upon it unless you know the strings you're comparing have been interned. The correct way to compare Strings for equal value is to use .equals.
It allow cause it probably faster to compare two address than comparing 2 string (but use it with caution, you probably never have to compare two String address).
It is sometime usefull to compare Object memories address, and as long as String is an object, eclipse allow you to compare using ==
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So I'm trying to check a list of account names to see if the username entered by the operator is in the database or not. At the moment I have:
for(int i = 0; i < rowCount; i ++){
System.out.println("Stored in array:" + accounts[i+1]);
System.out.println("name entered:" + LoginPage.usrname);
if(accounts[i+1] == LoginPage.usrname){
System.out.println("match");
}else{
System.out.println("no match");
}
}
I tried messing around with things like indexOf string and can't get anything to work. I'm sure there's a simple solution, just having trouble finding one. I don't understand why I can't compare a String array index to a String variable, seems like ti should be cake.
This is what you're looking for:
if(acounts[i+1].equals(LoginPage.usrname))
Using the == operator on Strings in Java doesn't do what you think it does. It doesn't compare the contents of the Strings, but rather their addresses in memory. The equals method compares the contents of the Strings.
As a note that may help you remember, this isn't anything particularly special about Strings. Strings are objects, and in Java, using == to compare objects of ANY type will present the same problem. If you want to compare the contents of two objects of a custom class you create, you'll have to write an equals method for that class. Strings work exactly the same.
String are unique reference type that behave like value type.
At Java when trying to compare String's using == operator, Java will try to check if both of the reference are equals, Not the strings.
In order to achieve a value type comparison you will be to use one of the following:
Method 1: str1.equals(str)
Method 2: str1.compareTo(str) == 0
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.