Abszol
Abszol

Reputation: 57

Comparing A String To Integer, Not Working?

Basically I am developing a program that involves matrices, I am AWARE AND DO NOT CORRECT that the matrix provided can be a simple array but that disproves what I am going for here.

Anyways the code provided below supplies 3 methods that each have a code that I have tried to compare the two values and in each case, it fails. If anyone can point out the error, that would be great.

public class TestingLength {

public static String[][] locatedNum = {{"1","2","3"}};

public static int num = 3;

public static void test() {

    System.out.println("Finding Number " + locatedNum[0][2] + " With Number " + num);

    if(locatedNum[0][2] == ""+num) {

        System.out.println("Example Worked!");

        return;
    }else
        System.out.println("Example Failed!");
}

public static void test2() {

    System.out.println("Finding Number " + locatedNum[0][2] + " With Number " + num);

    if(locatedNum[0][2].equals(num)) {

        System.out.println("Example Worked!");

        return;
    }else
        System.out.println("Example Failed!");

}

public static void test3() {

    String s = Integer.toString(num);

    System.out.println("Finding Number " + locatedNum[0][2] + " With Number " + num);

    if(locatedNum[0][2] == s) {

        System.out.println("Example Worked!");

        return;
    }else
        System.out.println("Example Failed!");

}

public static void main(String[] args) {
    test();
    test2();
    test3();
}

}

Upvotes: 1

Views: 58

Answers (2)

blueygh2
blueygh2

Reputation: 1538

Your first example works, if you change

if(locatedNum[0][2] == ""+num) {

to

if(locatedNum[0][2].equals(""+num)) {

Here, you are comparing Strings, and Strings should always be compared using .equals. Otherwise, you are comparing the String pointers, which are most of the time not the same.

Your second test works, if you change

if(locatedNum[0][2].equals(num)) {

to

if(Integer.parseInt(locatedNum[0][2]) == num) {

In this case, you are comparing Integer values, and == is a valid choice. However, you have to convert your String value from locatedNum to an Integer value as well.

Your third test works, if you change

 if(locatedNum[0][2] == s) {

to

 if(locatedNum[0][2].equals(s) {

If you are comparing strings, always use .equals instead of ==.

Upvotes: 2

Joshua Goldberg
Joshua Goldberg

Reputation: 5333

Your first example uses == to compare two Strings that are not the same object. (== says "are you the same object.) It would work fine with .equals.

Your second is stranger, comparing the String directly to the int without the ""+num conversion you used earlier to convert to a String

Your third has the same == problem.

Upvotes: 0

Related Questions