How to Compare a String with a Char

30
June 19, 2017, at 02:28 AM

Guys how do i compare a String with a char ? heres my code :

private String s;
private char c;
public K(String string, char cc){
    setS(string);
    setC(cc);
}
public void setS(String string){
    this.s = string;
}
public void setC(char cc){
    this.c = cc;
}
public boolean equals(K other){
    return s.equals(c);
}
public boolean try(){
    return s.equals(c);
}

if i call my method "try" it always returns me false even if i set both s = "s" and c = 's'.

Answer 1

The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.

Secondly think that there are a few things which you need to consider in your method.

If you compare things of two different types they will never be the same. A String can be null. How long the string is. The first char.

I would write the method like :

public boolean isSame() {
    if (s != null && s.length() == 1 { 
        return s.charAt(0) == c;
    }
    return false;
}
Answer 2

Either use char comparison (assuming s will always be of length 1):

return c == s.charAt(0);

Or use String comparison:

return s.equals(new String(new char[]{c}));
READ ALSO
What's wrong with my main method, and why is it throwing this exception? [on hold]

What's wrong with my main method, and why is it throwing this exception? [on hold]

I'm a new Java developer, writing my first real Java application, which is a calendar viewerHere's the code I wrote which is indicated as having errors:

61
Need to change the background of a TabbedPane in swing and backgroundColor of a panel

Need to change the background of a TabbedPane in swing and backgroundColor of a panel

Please find the imageI marked one tab which is colored blue

34
Unable to connect ThingSpeak jar files to java program

Unable to connect ThingSpeak jar files to java program

I used ant to build the buildxml file of ThingSpeak and it shows build successful

47
How to pass data stored in excel sheet as parameters under @Parameter in junit selenium?

How to pass data stored in excel sheet as parameters under @Parameter in junit selenium?

I have around 10 userIds which are pure numbers stored in a excel sheet and am using getUserIds() method to read input fileI want to pass them as Parameters under @Parameters instead of passing individual user ids which also i've tried but commented below

62