Bob
Bob

Reputation: 10795

type changing in Java

Could anybody tell how to fix the problem at line 10?

public class TestString {
    public static void main(String[] args) {
        String[] tahed = new String[10];
        String x;
        x = tahed[0] = "P";
        System.out.println(x);
        String nimi = "Paul";
        String[] eraldatud = nimi.split(" ");
        System.out.println(nimi.charAt(0));
        if (x == nimi.charAt(0)) //10
            System.out.println("True");
    }
}

Upvotes: 1

Views: 377

Answers (5)

billygoat
billygoat

Reputation: 21984

You are comparing string with char. It will never be equal. Try this:

 String[] tahed = new String[10];
        String x;
        x = tahed[0] = "P";
        System.out.println(x);
        String nimi = "Paul";
        String[] eraldatud = nimi.split(" ");
        System.out.println(nimi.charAt(0));
        char c = nimi.charAt(0);
        if (x.toCharArray()[0]==(c))//10
            System.out.println("True");

Please optimize code as necessary. This is just to put the point across.

Upvotes: 0

Shankar Raju
Shankar Raju

Reputation: 4546

public class TestString {
    public static void main(String[] args) {
    String[] tahed = new String[10];
    String x;
    x = tahed[0] = "P";
    System.out.println(x);
    String nimi = "Paul";
    String[] eraldatud = nimi.split(" ");
    System.out.println(nimi.charAt(0));
    if (x.equals(Character.toString(nimi.charAt(0))) //10
        System.out.println("True");
    }
}

Upvotes: 3

M. Jessup
M. Jessup

Reputation: 8222

The problem is you define x as a String, but you are comparing it to a char value (the type returned by charAt()). Depending on what your intent is you need to compare them as two strings or two chars:

if(x.charAt(0) == nimi.charAt(0)) //do a character comparison

OR

if(x.equals(nimi.substring(0, 1)) //do a string comparison

Upvotes: 0

Joel
Joel

Reputation: 16655

You have to convert the char returned by charAt to a String. I like to do that by just concatenating it to a string like this:

if (x.equals(""+nimi.charAt(0))) 

Upvotes: 3

aioobe
aioobe

Reputation: 420951

You're trying to compare a String (x) with a char (nimi.charAt(0)).

Either you need to convert the char to a String (and compare using .equals:

if (x.equals("" + nimi.charAt(0)))

or you need to convert the string to a char:

if (x.charAt(0) == nimi.charAt(0))

(but that may not be what you're after, since your basically checking if x starts with the same character as nimi)

Upvotes: 1

Related Questions