Converted charAt() doesnt equals to the same String [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
My problem is hidden in next code:
public class saturo {
public String primer, d;
public void start() {
primer = "545640";
//d = "0";
d = String.valueOf(primer.charAt(((primer.length())-1)));
if(d == "0"){
System.out.println("This is equal: d == " + d);
}else{
System.out.println("This is not equal: d == " + d);
}
}
public static void main(String args[]) {
new saturo().start();
}
}
So as you see, the problem is that if i declare String d as "0" than the program will execute it as d is equal to "0" and return true;
But if i get character "0" from a String, convert it to String, and check if this equals to "0" then i have got a false.
I have checked if there is something wrong with character encode, but not, its right in any case. No type mismatches.
Where in this the logic?

If you want to compare the value of 2 strings, you need to use .equals()
So you would do:
if(d.equals("0"){
// your code here
}
Using == compares the strings by reference (same spot in memory) where .equals() compares the value of the strings.

use .equals not == you are comparing by reference not value

Related

Java If Else Text Based on Other Text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to have a text-box populate with X if another text-box has a certain value, else Y. However, it's populating with X or Y seemingly randomly. d4 is my button, d4result is where it populates the result, d4txt1 is where I want to see a 1 or 0, depending.
d4.setOnClickListener {
if (d4result.text.toString() == "1") {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
So if d4result is populated with 1, I want d4txt1 to populate with 1, otherwise it should be zero. But when I try it, I get 1 or 0 and I can't notice a pattern as to when/why.
Use equals instead of ==. == operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
d4.setOnClickListener {
if (d4result.text.toString().equalsIgnoreCase("1")) {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
Java is tricky about that. The == operator compares the two object pointers, not their values. It's fine for integers and floats but almost never useful for strings.
Instead use the .equals() method or the .equalsIgnoreCase() method:
if (d4result.text.toString().equalsIgnoreCase("1")) { ...

Java will not recognize "(" and ")" strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Java comparison with == of two strings is false? [duplicate]
(12 answers)
Closed 9 years ago.
I am trying to interpret a string input from the user. I take in a phrase, split it into an array, and compare each value in the array to ")" as a boolean. The problem is it will read the string "( 3 + 5 )", and I know that the array that takes in the string is ["(","3","+","5",")"] and when I print out position 0 and 4 of the array, it returns "(" and ")". I know that these are type string of length 1, however, when I compare the exact same values to the "(" ")" in the code, it returns false.
Any idea what's wrong? Here's my code. The parts that I am having trouble with are the if statements.
public String buildExpression(String E){
String[] exprArr=E.split(" ");
int len=exprArr.length;
BTStacker S = new BTStacker();
String val;
for (int i=0; i<len; i++){
val=exprArr[i];
System.out.println(val);
if (val=="("){
System.out.println("2");
}
else if(val != ")"){
BSTree T=new BSTree();
BSTNode v=new BSTNode(val,null);
T.addRoot(v);
S.push(T);
}
else{
BSTree Ty = S.pop();
BSTree T=S.pop();
BSTree Tx=S.pop();
T.attach(T.root(),Tx,Ty);
S.push(T);
}
}
}
When you compare Strings in Java, you need to use .equals(), not ==, because Strings are Objects.
NEVER compare strings using ==.
Always compare using the equals method.
val.equals("(")
Note that when using "==" to compare string objects, you are not comparing it's values but it's references.

Why doesn't this code terminate my program? Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to implement the System.exit(0); in java to terminate my program when the word "exit" is typed into the console. I wrote the following method:
public static void exit(){
Scanner input = new Scanner(System.in);
Str1 = input.next(String);
if (str1 = "exit"){
System.exit(0);
}
else if (str1 = "clear"){
System.out.println("0.0");
}
}
and it doesn't seem to be working. Does anyone have any suggestions?
Thanks
P.S the "clear" is just supposed to return 0.0 when "clear" is entered into the console, if you could not already tell.
Compare strings with equals() not with ==.
The reason is that == just compares object references/primitives,where as String's .equals() method checks equality.
if (str1.equals("exit")){
}
and also
else if (str1.equals("clear")){
}
Might useful :What are the benefits of "String".equals(otherString)
if(str.equals("exit"))
or
if(str.equalsIgnoreCase("exit"))
or
if(str == "exit")
instead of
if (str1 = "exit"){
With if (str1 = "exit") you use an allocation instead of a compare.
You can compare with the equals() method.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
So use:
if ("exit".equals(str1)){
}
Besides equals(), the input.next(String pattern); require pattern not String data type
Change your code to:
public static void exit(){
Scanner input = new Scanner(System.in);
str1 = input.next(); //assumed str1 is global variable
if (str1.equals("exit")){
System.exit(0);
}
else if (str1.equals("clear")){
System.out.println("0.0");
}
}
Notes : http://www.tutorialspoint.com/java/util/scanner_next_string.htm

Java string format returns nothing [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to get the returned value from a class, however I believe the string.format() is causing an error resulting in no value to return.
Class:
public class FilterTime {
public String getData(String day, Integer time){
// define the result
String result = "";
String convertedDay = "";
if(day == "Friday 30th August"){
convertedDay = "30";
}
if(day == "Saturday 31st August"){
convertedDay = "31";
}
if(day == "Sunday 1st September"){
convertedDay = "01";
}
if(time == null){
result = "http://www.website.org/json.php?f=%s&type=date".format(convertedDay);
Log.d("RESULT", "r:" + result);
}else{
result = "http://www.website.org/json.php?f=%s&time=#d&type=dateAndTime".format(convertedDay, time);
Log.d("RESULT", "r:" + result);
}
return result;
}
}
When I trace result in my Activity:
FilterTime filterTime = new FilterTime();
String filteredURL = filterTime.getData(dayFilter, timeFilter);
When I trace filteredURL it returns nothing at all. So I then put the Log.d() into the class and I found that when tracing the following it also returns nothing:
if(time == null){
result = "http://www.website.org/json.php?f=%s&type=date".format(convertedDay);
Log.d("RESULT", "r:" + result);
}else{
result = "http://www.website.org/json.php?f=%s&time=#d&type=dateAndTime".format(convertedDay, time);
Log.d("RESULT", "r:" + result);
}
I cannot understand where the error is coming from because there are no errors, just a warning saying it should be accessed in a static way, but I think the error resides in the if statement.
Use equals() to compare the contents of the String :
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Hence change your code to :
if("Friday 30th August".equals(day)){
convertedDay = "30";
}
== operator compares object references, variable which contains a reference to an object. It checks if the references point to the same object.
P.S.:- Invoked equals() on the String literal to avoid any NPE due to null day.
You have incorrect String comparison, instead of == use equals.
format is printing nothing since convertedDay remains empty "" due to invalid String comparison.
String.format() is a static method. Don't call it on a String object, just call it directly like this:
String.format("http://www.website.org/json.php?f=%s&type=date", convertedDay);
That should do the formatting like you wanted

How to compare strings that were created by substring? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 10 years ago.
I'm wondering why it doesn't work, and why I cant't use the CHAR data type for variables a and b. The point is, how to compare the first and the last digits of number (pr) accordingly such way.
String a, b;
for (int i=100; i<1000;i++) {
for (int j=100; j<1000;j++) {
pr=j*i;
a = String.valueOf(pr).substring(0, 1);
b= String.valueOf(pr).substring(4, 5);
if ((a==b) ) {
System.out.println(pr);
}
}
}
use equals functions
a.equals(b)
If you want to ignore case then use
a.equalsIgnoreCase(b)
This is not JavaScript to use == for String comparison.
Go for equals method
In Java, operator == compares object identities, so if there are two objects of type String with the same content, == will return false for them:
String x = new String ("foo");
String y = new String ("bar");
if (x == y)
System.out.println ("Equal");
else
System.out.println ("Now equal"); // This will be printed
In order to compare String object by content, not by identity, you need to use equals() method like this:
if (x.equals (y))
System.out.println ("Equal"); // This will be printed
else
System.out.println ("Now equal");
Note, that if x is null, then x.equals (y) will throw NullPointerException while x == y will return false if y is not null and true if y is null. To prevent NullPointerException you need to do something like this:
if (x == null && y == null || x != null && x.equals (y))
System.out.println ("Equal"); // This will be printed
else
System.out.println ("Now equal");

Categories