开发者

type changing in Java

开发者 https://www.devze.com 2023-02-22 01:25 出处:网络
Could anybody tell how to fix the problem at line 10? public class TestString { public static void main(String[] args) {

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 =开发者_C百科 nimi.split(" ");
        System.out.println(nimi.charAt(0));
        if (x == nimi.charAt(0)) //10
            System.out.println("True");
    }
}


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


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


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)


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消