Ternary operator to return value- Java/Android

后端 未结 5 709
情深已故
情深已故 2021-02-07 01:13

Just switched to Java from php

I encountered following issue

I want to rewrite

if(usrname.equals(username) && (passwd.equals(password))){         


        
5条回答
  •  青春惊慌失措
    2021-02-07 02:14

    lets say I need

      (usrname.equals(u) && passwd.equals(p)) ? return "member" : return guest";
    

    The correct syntax is:

       return (usrname.equals(u) && passwd.equals(p)) ? "member" : "guest";
    

    The general form of the ternary operator is

       expression-1 ? expression-2 : expression-3
    

    where expression-1 has type boolean, and expression-2 and expression-3 have the same type1.

    In your code, you were using return statements where expressions are required. In Java, a return statement is NOT a valid expression.

    1 - This doesn't take account of the conversions that can take. For the full story, refer to the JLS.


    Having said that, the best way to write your example doesn't uses the conditional operator at all:

       return usrname.equals(username) && passwd.equals(password);
    

提交回复
热议问题