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

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");

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")) { ...

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

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

Does "==" only apply to certain data types? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
In this program below:
public class medianTemp {
public static void main(String[] args){
int length = args.length;
int[] n = new int[length];
n[0] = Integer.parseInt(args[0]);
System.out.print(n[0] + " ");
for (int i = 1; i < length; i++ ){
String c = args[i];
if (c.equals(".")){
n[i] = n[i-1] + 0;
System.out.print(n[i] + " ");
}
if (c.equals("+")){
n[i] = n[i-1] + 1;
System.out.print(n[i] + " ");
}
if (c.equals("-")){
n[i] = n[i-1] - 1;
System.out.print(n[i] + " ");
}
Inside the for loop and inside the if statements. If I use for example args[i] == "." (instead of converting args[i] to string), the code above doesn't work and only the initial integer is displayed. Can someone please tell me why this happens?
== compares objects based on their memory location when they are not primitives. Strings are not primitives, so while the content of 2 String objects may be equal the address of each one in memory is different and == returns false.
In java, String objects (and nearly all objects) need to be compared with equals(). Two String objects may have the same value but be different objects (i.e. duplicates in memory a la new String()). The == comparison compares references.
You just need to use equals for string comparison.
Example from this website : http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);
It returns false, while the following code returns true.
String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));
== is a relational operator, referring to the relationships that values can have with one another.
Also, the == operator obviously means "Equal To" and only works for raw data types.
These types include double, int, and float. However, the == operator will not work in a boolean expression (only true/false works).
So in sum, it's really how you put your program together to get this operator to work. I recommend reading JAVA programming books such as the "JAVA 2" Series. Hope this helped!

How to use the while statement for text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to make a simplified version of Black Jack in Java using eclipse. I'm trying to make it so the player types 'hit' or 'stand', and while they haven't, it keeps prompting them to do so.
while (hitorstand != ("hit") || hitorstand != ("stand"))
{
System.out.println("Would you like to hit or stand?(1 for hit, 2 for stand)");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
}
if (hitorstand.equals("hit"))
{
playercard3 = random.nextInt(10) +2;
System.out.println(""+playercard3);
}
else if (hitorstand.equals("stand"))
{
System.out.println("You had a total value of " + playercardtotal + ".");
if (hiddendealercard == card2)
When I run it, no matter what I type it cannot escape the while loop. I know it would work if I used numbers but I really want to learn how to use words as input.
while (hitorstand != ("hit") || hitorstand != ("stand")) // This is not the right way
Use the equals() method for String value comparison. == is for object reference comparison.
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")) // This is
I'm not sure why you'd use the != in the while loop condition, whereas you've properly used (hitorstand.equals("hit")) just below the while, in a if statement.
Also, there seems a minor mistake in the while loop block.
hitorstand.toLowerCase(); // This does nothing
As Strings are immutable in java, you need to assign back the changed string to be able to see the changes
hitorstand = hitorstand.toLowerCase(); // Assigning back the lowercase string back to hitorstand
You need to use .equals(..) instead of ==. This is because == is used for reference equality, while .equals() is simply for value equality.
For example:
while(!hitorstand.equals("hit") || !hitorstand.equals("stand"))
Comparing hitorstand != ("hit") you actually compare object references not the String value itself. To compare strings you need to use equals method. In java every class inherits equals ( from Object ) and it can be overriden for custom object comparison
Try this:
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")){
Adding to the answers, a good rule of thumb is to use .equals() with strings and == with integer values or variables with integer values (or the value null).
One way you could do this would be to use a character. For example: instead of
while (hitorstand != ("hit") || hitorstand != ("stand"))
you could have it check for the first character in the string using the charAt() command with the index of the string in the parenthesis. So since your looking for the first character, it would be at index 0.
while (x != 'h' || x != 's')
x being a char.
Inside your while loop,
System.out.println("Would you like to hit or stand?");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
x = x.charAt(0); // you would just add this line. This gets the character at index 0 from the string and stores it into x. So if you were to type hit, x would be equal to 'h'.
Your if statement could stay the same or you could also change the condition to (x == 'h') and (x == 's'). That's up to you.

If condition does not work correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I have written this code:
public String[] removeDuplicates(String[] input){
int i;
int j;
int dups = 0;
int array_length = input.length;
for(i=0; i < array_length; i++){
//check whether it occurs more than once
for(j=0; j < array_length; j++){
if (input[i] == input[j] && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
} // for j
} // for i
System.out.println("Category contained " + dups + " duplicates.");
return input;
}
which is supposed to check whether an array of strings contains one or more duplicates. However, even when I define the array like this:
String[] temp = new String[2];
temp[0] = "a";
temp[1] = "a";
The if condition is not "triggered". Did I misunderstand how && works? In my opinion, the program should first check whether the two strings are identical (which they are...) and then whether the two indices are the same. If not, it should perform the operations.
However, the programs seems to think otherwise.
One of the most common mistakes in Java is to assume that a String is an object when its a reference to an object. When you use == you are comparing references, not their contents. This is why .equals() is required to compare their contents.
BTW you can remove duplicates with
public static String[] removeDuplicates(String[] input){
return new HashSet<String>(Arrays.asList(input)).toArray(new String[0]);
}
The == operator in Java checks if the two objects are the same, not that they are equal. Two strings may have identical content, and compare negatively for equality. You need to use equals instead:
if (i != j && input[i].equals(input[j])){
}
If null values are allowed among the input elements, you need to add a null check to your condition to avoid an exception:
if (i != j && input[i] != null && input[i].equals(input[j])){
}
Never use == to check that two objects have the same value. Use equals()
== will check their memory positions (if both objects are in fact only one), equals() is the method that will tell you if both represent the same information.
While working with Strings (and any non-primitive type), remember that == makes a comparation by reference, not by value. Use equals() instead.
if (input[i].equals(input[j]) && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
As a rule of thumb, use == when you want to check if two objects are EXACTLY the same object (you can think of it as if both pointers where referencing the same address).
You should use String.equals for checking string content. The == operator just checks the object reference:
if (input[i] != null && input[i].equals(input[j]) && i != j) {

Categories