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"))
Related
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.
Is there a way to make sure that the + plus operator is used to concatenate a String as opposed to being used as an arithmetic operator, for example this won't work because inGame is a boolean and e.getSource() == list is also a boolean.
System.out.println((e.getSource() == list) + inGame);
but
System.out.println(e.getSource() == list +""+ inGame);
this will, is there someway for the top example to work e.g. a way to tell the compiler to use the operator as concatenate operator as opposed to the arithmetic one ?
You could use a StringBuilder to concatenate your Strings (and other stuff) properly. After all, that's what internally Java does when you use the "+".
System.out.println(new StringBuilder().append(e.getSource() == list).append(inGame).toString());
You can use String.valueOf():
System.out.println(String.valueOf(e.getSource() == list) + String.valueOf(inGame));
Or, if you're just printing:
System.out.print(e.getSource() == list);
System.out.println(inGame);
Lastly, printf() is also an option:
System.out.printf("%b%b\n", e.getSource() == list, inGame);
This is useful if you're trying to print in more complicated formats.
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));
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I compare strings in Java?
I am trying to make it so that when I type hope, b will save hope and then it will recognize c == b, and you get the picture. What do I do? I am new to Java and I apologize if this is a no brainer.
package encryption;
import java.util.Scanner;
public class Encrypt
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String test1 = new String("Enter now: ");
String d = new String("Success!");
String e = new String("Failure");
String b = new String();
String c = "hope"
System.out.print("Enter text: ");
b = scan.next();
if (b == c)
System.out.println("\"" + d + "\"");
else
System.out.println("\"" + e + "\"");
}}
Use if b.equals(c) because b==c compares references in java. It tells that if both the objects are referring to same memory locations or not.
So, if you need to check whether their values are equal always use equals method.
if (b == c)
Use equals instead to compare strings:
if (b.equals(c))
== compares the references, not the values so you're getting false every time. Equals compares the values.
This link provides a good explanation between ==, equals, compareTo, ...
To test the equivalence of Strings in Java you want to use the equals method:
if(c.equals(b)) {
...
}
The == operator tests to see if both variables point to the same place in memory. You have two Strings that have the same "value" (read:text), but are stored in two different places in memory.
c == b tests reference equality -- i.e. do the references point to the same object. You want equals as in b.equals(c)
Two things:
Don't compare Strings using a == b, use a.equals(b). The == operator asks if two Strings are the same physical chunk of memory; the equals() method asks if they contain the same characters. You want that second one!
You never need to -- nor should you -- use new String() in Java; just a double-quoted string like "hope" is a String object. Using new String() just creates unneeded objects and bogs things down.
b==c checks whether b and c reference the same string, while b.equals(c) check whether their values are equal, which is what you're trying to do.
Your problem is not proper reading documentation.
Use String.equals() instead.
I'm having a minor issue with Java String comparisons.
I've written a class which takes in a String and parses it into a custom tree type. I've written a toString class which then converts this tree back to a String again. As part of my unit tests I'm just checking that the String generated by the toString method is the same as the String that was parsed in the first place.
Here is my simple test with a few printouts so that we can see whats going on.
final String exp1 = "(a|b)";
final String exp2 = "((a|b)|c)";
final Node tree1 = Reader.parseExpression2(exp1);
final Node tree2 = Reader.parseExpression2(exp2);
final String t1 = tree1.toString();
final String t2 = tree2.toString();
System.out.println(":" + exp1 + ":" + t1 + ":");
System.out.println(":" + exp2 + ":" + t2 + ":");
System.out.println(exp1.compareToIgnoreCase(t1));
System.out.println(exp2.compareToIgnoreCase(t2));
System.out.println(exp1.equals(t1));
System.out.println(exp2.equals(t2));
Has the following output; (NB ":" - are used as delineators so I can ensure theres no extra whitespace)
:(a|b):(a|b):
:((a|b)|c):((a|b)|c):
-1
-1
false
false
Based on manually comparing the strings exp1 and exp2 to t1 and t2 respectively, they are exactly the same. But for some reason Java is insisting they are different.
This isn't the obvious mistake of using == instead of .equals() but I'm stumped as to why two seemingly identical strings are different. Any help would be much appreciated :)
Does one of your strings have a null character within it? These might not be visible when you use System.out.println(...).
For example, consider this class:
public class StringComparison {
public static void main(String[] args) {
String s = "a|b";
String t = "a|b\0";
System.out.println(":" + s + ":" + t + ":");
System.out.println(s.equals(t));
}
}
When I ran this on Linux it gave me the following output:
:a|b:a|b:
false
(I also ran it on Windows, but the null character showed up as a space.)
Well, it certainly looks okay. What I would do would be to iterate over both strings using charAt to compare every single character with the equivalent in the other string. This will, at a minimum, hopefully tell you the offending character.
Also output everything else you can find out about both strings, such as the length.
It could be that one of the characters, while looking the same, may be some other Unicode doppelganger :-)
You may also want to capture that output and do a detailed binary dump on it, such as loading it up into gvim and using the hex conversion tool, or executing od -xcb (if available) on the captured output. There may be an obvious difference when you get down to the binary examination level.
I have some suggestions
Copy each output and paste in Notepad (or any similar editor), then
copy them again and do something like this
System.out.println("(a|b)".compareToIgnoreCase("(a|b)"));
Print out the integer representation of each character. If it is a weird unicode, the int representation will be different.
Also what version of JDK are you using?