String compare function equals not giving correct result - java

I am using eclipse with java
I am trying to compare two string removing all the space between them.
Here is my code
First I am removing whitespace within the Strings.
System.out.println("["+StringUtils.deleteWhitespace(s4)+"]");
System.out.println("["+StringUtils.deleteWhitespace(s3)+"]");
// comparing Strings
if(s4.equals(s3))
{
System.out.println("Text Match");'
}
Below is the output from lines 1 and 2 that is displaying on Eclipse console:
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
From what I can see, there is no difference between two string yet it is displaying string as a mismatch.

You did not assign the results of the deleteWhitespace() operation to anything. Your two strings will therefore remain unchanged.
Store the result like so, before printing it:
s4 = StringUtils.deleteWhitespace(s4);

The method StringUtils.deleteWhitespace(s4) does not change the String referenced by s4 (Strings are immutable) but returns a new string.
If you do the following code:
s3 = StringUtils.deleteWhitespace(s3);
s4 = StringUtils.deleteWhitespace(s4);
if (s4.equals(s3)) {
System.out.println("Text Match");'
}
Then you will see that the two strings are really equal and the "Text Match" is printed.

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

Remove all numbers and "{" from a String Array

I am trying to remove all non numeric characters from the String Array as require to compare it with the list of numbers. The split works but I am not able to compare the two Sets
for(String w:a1)
{
w=w.replaceAll("[^\\d.]", "");
if(dContacts.getNumber().equals(w))
{
System.out.println("Compared1234567");
}
System.out.println("---6545678909876789876hijkhijkhijkjh"+dContacts.getNumber());
System.out.println("Arraylistextract"+w);
}
In Java, Strings are immutable. This means that w.replaceAll("[^\\d.]", ""); will create a different String, and w will remain the same. Assign that expression to w to store it:
w = w.replaceAll("[^\\d.]", "");
You cannot modify a string without reassigning it to either the same variable or a new one.
String is Immutable so if you are calling some function then it will not change in same object.
you have to change this line to
w= w.replaceAll("[^\\d.]", "");

What will be the output from the following three code segments?

I'm currently on a self learning course for Java and have gotten completely stumped at one of the questions and was wonder if anyone can help me see sense...
Question: What will be the output from the following three code segments? Explain fully the differences.
public static void method2(){
String mystring1 = "Hello World";
String mystring2 = new String("Hello World");
if (mystring1.equals(mystring2)) {
System.out.println("M2 The 2 strings are equal");
} else {
System.out.println("M2 The 2 strings are not equal");
}
}
public static void method3(){
String mystring1 = "Hello World";
String mystring2 = "Hello World";
if (mystring1 == mystring2) {
System.out.println("M3 The 2 strings are equal");
} else {
System.out.println("M3 The 2 strings are not equal");
}
}
The answer I gave:
Method 2:
"M2 The 2 strings are equal"
It returns equal because even though they are two separate strings the (mystring1.equals(mystring2)) recognises that the two strings have the exact same value. If == was used here it return as not equal because they are two different objects.
Method 3:
"M2 The 2 strings are equal"
The 2 strings are equal because they are both pointing towards the exact same string in the pool. == was used here making it look at the two values and it recognises that they both have the exact same characters. It recognises that Hello World was already in the pool so it points myString2 towards that string.
I was pretty confident in my answer but it's wrong. Any help?
Both will return true.
1) 2 new string objects are created but use .equals which means their actual value is compared. Which is equal.
2) 1 new string object is created because they are both constant at compile time. This will result in them pointing to the same object.
This sentence might be your issue:
== was used here making it look at the two values and it recognises that they both have the exact same characters.
== checks for reference equality whereas you're describing value equality.
First two are equal, second two are not. But unless you put it into main() method there will be no output at all.
EDIT: second pair are not the same because "==" compares addresses in memory.
You're right about the first one.
However the second would return "M3 The 2 strings are not equal".
This is because == tests for reference equality and since they are two different variables, they would not equal.

Alternative to substring

I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil
You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.
Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}
Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));

Beginners Java Question (string output)

So I'm reading input from a file, which has say these lines:
NEO
You're the Oracle?
NEO
Yeah.
So I want to output his actual lines only, not where it says NEO. So I tried this:
if(line.trim()=="NEO")
output=false;
if (output)
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the line if 'output' is true
But thats not working out. It still prints NEO. How can I do this?
When comparing strings in Java you have to use the equals() method. Here's why.
if ( "NEO".equals(line.trim() )
I think you're looking for line.trim().equals("NEO") instead of line.trim() == "NEO"
That said, you can get rid of the output variable by instead doing
if(!line.trim().equals("NEO"))
{
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the if it isn't "NEO"
}
Strings are objects in Java. This means you can't just use the == operator to compare them, since the two objects will be different even if they both represent the same string. That's why the String object implements an equal() method, which will compare the contents of the objects, instead of just their memory addresses.
Reference
String.equals() docs
In Java, Strings are objects. And the == operator checks for exact equality.
In other terms
final String ans = line.trim();
final String neo = "NEO";
if (ans == neo) ...
implies you want to check that the ans and the neo objects are the same. They are not, since Java allocated (instantiated) two objects.
As other said, you have to test for equality using a method created for the String object, that actually, internally, checks the values are the same.
if (ans.equals(neo)) ...
try the following:
if(line.trim().equals("NEO"))

Categories