error: incompatible types: unexpected return value Char compare to String

后端 未结 3 1238
眼角桃花
眼角桃花 2020-12-12 08:04

I am trying to compare char to a String but getting an error. Error

error: incompatible types: unexpected return value

code:



        
相关标签:
3条回答
  • 2020-12-12 08:36

    The type of main() is void (public static void main(String args[]) {) and therefore you cannot return a value from it.

    The actual error I get when I run this is:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Void methods cannot return a value
    
    0 讨论(0)
  • 2020-12-12 08:51

    The main method can not return anything, it has a void type. You can write a separate function that returns that value, assign the value to a variable, or just print the value.

    public boolean strChar(String s, String p){
        return p.equals(new String(new char[]{c}));
    }
    

    or

    System.out.println(p.equals(new String(new char[]{c})));
    

    or

    boolean equals = p.equals(new String(new char[]{c}));
    
    0 讨论(0)
  • 2020-12-12 08:57

    Characters are not objects and can / should be compared using the == operator. There is no need to build a string each time. Also the main method can't return any value, it is void.

    0 讨论(0)
提交回复
热议问题