This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
OK, my first question in stackOverflow.
This is something that I left me completely baffled.
Java (I use android Studio), I write the following code:
Integer aNumber = 200;
String aNumberInString;
aNumberInString = Integer.toString(aNumber);
Boolean result;
if(aNumberInString == "200"){
result = true;
} else {
result = false;
}
Log.i("result:",result+"");
OK, logic and what I expect is that the condition is true... But NO! it fails.
I was really shocked by this behavior, then investigate a little more, and run the code in debug mode step by step.
when I get to the condition, I inspect the value of "aNumberInString" and to my surprise, this is what I find:
OK, so the first thing I think is: "Integer.toString ()" are doing something wrong.
Let's try another way: "String.valueOf ()"
Run in debug mode, and:
THE SAME! and fails, of course.
Obviously fails because it compares different characters, and in Internet I found a way to fix it,
string.replace ("\\ u0000", "");
but my question is not how to fix it, is:
Why is this happening?
Is there a correct way to prevent this from happening?
From already thank you very much to all,
Regards, Nicolas
You are doing a reference comparison. For comparing Strings, you need to call equals. By doing == with an Object, you are asking Java to make sure they are the same object, not if they have the same value.
Change:
if(aNumberInString == "200"){
To this:
if(aNumberInString.equals("200") {
Or better yet, to reduce the chance of a NullPointerExcpetion:
if("200".equals(aNumberInString))
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new to java. Trying to create a function to remove a given string "arg" from myString which is previously set and return a new string not affecting myString. I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string. so if arg has a 7 in it that should still be included in the final string. characters being removed are case insensitive as well.
I have edited the previous code and post, i can now run my code but I am not getting the correct results, I am trying to remove all numbers from arg before using it to remove all the characters. myString method is previously defined and working properly to return a string.
For examplecurrent string "my lucky numbers are 6, 8, and 19.", calling remove("ra6") would return "my lucky numbes e 6, 8, nd 19."
or "my lucky numbers are 6, 8, and 19.", calling remove("6,.") would return "my lucky numbers are 6, 8, and 19."
thank you!
public String remove(String arg) {
char[] charArray=arg.toCharArray();
String result="";
String newString="";
for (int i = 0; i < charArray.length; i++) {
if (!Character.isDigit(charArray[i])) {
result = result + charArray[i];
return result;}}
if (myString==null || myString=="") {
this.myString="";}
if (myString!=null) {
newString= myString.replaceAll(result,"");}
return newString;
}
Here is one way using streams. Just create a stream of characters via the chars() method and allow only letters to pass thru. Then each character to a String and join them together. Then remove that result from the original passed string.
String myString = "abcdTLK123efgh";
String arg = "TLK###123";
String result = remove(arg, myString);
System.out.println("Result = " + result);
prints
Result = abcd123efgh
The method
I modified the method to accept two strings.
the one to remove characters(arg).
and the from which to remove modified arg from myString
it works by
streaming all the characters of arg.
filtering out all but letters and digits
joining them as a string.
and then removing that filtered string from the myString.
public static String remove(String arg, String myString) {
if (myString == null || myString.isBlank()) {
return "";
}
return arg.chars().filter(
ch -> Character.isLetter(ch))
.mapToObj(Character::toString)
.collect(Collectors.collectingAndThen(
Collectors.joining(),
str -> myString.replace(str, "")));
}
Note: If myString is null then assigning an empty string to it will contain nothing to change. Nor an initial empty string. So I just returned an empty String if those conditions existed.
I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string.
The good news is that you can solve it yourself.
The bad news is that the code above is in such a mess that it would be difficult for you to fix it by yourself. (Given your current level understand of Java syntax, way of working, etcetera.)
(Also, there is a long more wrong than the "if it were not for ..." ...)
So here is what I advise you to do.
Save a copy of the current version of the (entire) class somewhere safe so that you can look it again if you need to, or revert to it.
Develop a model of what the method needs to do and how it will do it; see below.
Delete all lines of code between the first { and last } shown in the question. Yes. Delete them.
Compose the new version of the code, one line at a time. As follows:
Add a line.
Compile the code (or let the IDE compile it for you).
Read the compilation error(s) that just appeared.
Understand the compilation errors.
Make the necessary changes to fix the compilation errors. Don't rely on your IDE's facility for suggesting corrections. (The IDE doesn't understand your code, what you are going to add next, or what you are trying to achieve. Its suggestions are liable to be unhelpful or even wrong.)
Repeat until you have dealt with all of the compilation errors that were introduced.
Now you are ready to add another line.
Once you have a complete method, you can then try to run it.
You will most likely find that the code doesn't work. But at least it will be valid Java code. And in the process of doing 4. above, you will (hopefully!) have learned enough Java syntax to be able to read and understand the code that you wrote. And 2. will help you understand what the code you are writing should do.
My other observation is that it looks like you have been adding and removing statements to this code with no clear understanding of what they do or what needs to happen. Maybe you started with some code that did something else ... correctly ... but it is hard to tell now.
Changing things randomly to try to make the code work is not a sensible approach. It rarely works. You need to have a model (or plan) in your head or on paper (e.g. as pseudo-code or flowcharts) about how the code ought to work.
Programming is about 1) developing the model, then 2) translating the model into code. The first part is the hard (and interesting) part. But if you skip the first part, the second part is an essentially random process, and unlikely to succeed.
The problem with starting with someone else's code is that you risk not developing a mental model of how that code works. Let alone the model that you are aiming for.
Finally, a professional programmer will use a version control system for their source code, and make relatively frequent commits of their code to their repository. Among other things, that allows them to quickly "roll back" to an earlier version if they need to, or keep track of exactly what they changed.
It is probably too early for you to learn about (say) using Git ... but it would help you solve your problem if you could just "roll back" all of the changes where you were "messing" with the code to get it to work.
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
This question already has answers here:
If statement executing all conditions
(9 answers)
Closed 4 years ago.
Got a basic if statement question, so I have an if statement in Java as shown here:
if (
!isOmitted(word,map.get(word.length()+1)) &&
!isInserted(word,map.get(word.length()-1)) &&
!isTransposed(word,map.get(word.length())) &&
!isSubstituted(word,map.get(word.length())) &&
!isCapital(word,map.get(word.length())))
{
noSuggestion=true;
}
where each individual method works perfectly as desired. Is there any way for java to check all conditions even when one is false? I know that the nature of the && operator is that as soon as a condition does not hold true, there is no point in checking the remaining conditions, as the entire condition is going to be set to false, but I was hoping I could do something like this in order to keep my code someone cleaner. I know I can use boolean variables, and assign the returned value to 5 different variables, but is there any other work around to force every condition to be checked? Thanks a lot in advanced
A single & is a non-short-circuit operand - ie both sides are evaluated irrespective of whether required.
More info here - https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.2
However, this sounds like a poor design. In fact, some code analysis tools would automatically flag these operators as suspicious for this reason. Typically you would want to call each method as they make some change to the state of your objects, which is not something you would expect in an if statement. But your method names do not suggest this. What are you trying to achieve?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I wrote a simple code just to check the values between textfields and compared whether they are the same or not. I want them to be the same, if not it will produce an error. It's about rewriting an email.
String a = studentemail.getText();
String b = rewritestudentemail.getText();
if(a != b){
JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly.","Error!",JOptionPane.OK_OPTION);
}
The program persists that there is an error even though I indicated the same string values in both of the fields. Why's that?
Change your conditional to be this:
if(!a.equals(b))
{
JOptionPane.showMessageDialog( null, "Student Email rewritten
incorrectly.","Error!",JOptionPane.OK_OPTION);
}
Make sure you have the ! before a.equals(b)) since you only want the error to appear when they are not equal.
rather layout your logic like this:
if (!a.equals(b)){
//JoptionPane...
}
In java two strings are compared by using the ".equals()" function.
Try:
if (!a.equals(b)) {
...
I am getting the occasional odd result from String.equals(String).
here is the code:
boolean equals(OutputHolder other){
boolean result=true;
if( ! this.speciesEng.equals(other.speciesEng))
result=false;
else if( ! this.date.equals(other.date))
result=false;
else if( ! this.gridRef.equals(other.gridRef))
result=false;
else if( ! this.recorder.equals(other.recorder))
result=false;
return result;
}
All pretty straight forward but on some objects .equals() returns false on what appear to be 2 identical strings.
This is a screenshot of the Expressions watchlist when the error occurs. As you can see this.speciesEng.equals(other.speciesEng) is returning false despite the fact that both strings appear the same.
The strings are initially from the same string resource but both have passed over an XMPP connection and back.
EDIT: To pass them over the XMPP connection, they have been concatenated with other strings to represent the whole OutputHolder. They are then separated on return using .substring(start,end). It occurred to me that it might make a difference if I made a new string from the substring but that didn't have any effect. Neither did trimming them.
I am at a loss as to how to proceed with debugging the problem. Any help or suggestions welcome.
There might be some whitespaces in there. Use String#trim method prior to calling equals.
Make sure there are no trailing spaces. So better use trim method on the strings before comparing them using equals method.
I think you should first trim both the strings and get rid of additional spaces.
That way you will be able to equate both the Strings properly.
Example Code:
String yourString = "Your String ";
//Trim the String and get rid of extra spaces before doing any comparisons.
yourString.trim();
//After trimming it, do the comparisons.
if(yourString.equalsIgnoreCase("other trimmed string"))
{
.....
}
I hope this helps.
After god knows how many hours copying and pasting from the debugger to a hex editor I have found the problem and a solution that works.
As suggested the problem was whitespaces but not in the way I or (I think) others suspected.
For some reason that I have failed to get to the bottom of, I am getting non-breaking whitespaces (0x00A0) in my strings instead of normal whitespaces (Ox0020). This appears to be happening more or less at random and I haven't found the section of code responsible yet.
The work around at the moment is to start my equals() method with:
speciesEng=speciesEng.replace((char)0x00a0,(char)0x0020);
other.speciesEng=other.speciesEng.replace((char)0x00a0,(char)0x0020);
speciesEng=speciesEng.trim();
other.speciesEng=other.speciesEng.trim();
Far from elegant but it works for the moment. I'll leave the question open for a couple of days in case anyone has more to add.
Thanks to all for the answers.
boolean equals(OutputHolder other){
boolean t1 = speciesEng.equals(other.speciesEng);
boolean t2 = date.equals(other.date);
boolean t3 = gridRef.equals(other.gridRef);
boolean t4 = recorder.equals(other.recorder);
return t1 && t2 && t3 && t4;
}