Ternary operator to return value- Java/Android

后端 未结 5 697
情深已故
情深已故 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 01:56

    By the way you can simplify:

    return (usrname.equals(username) && passwd.equals(password) )? return true : return false;

    To:

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

    The ternary operator work similar in php than Java, I think you have made a silly mistake, maybe "username" have a space or another white character

    String a1 = "a";
    String b1 = "b";
    
    String a2 = "a";
    String b2 = "b";
    
    System.out.println((a1.equals(a2)&&b1.equals(b2))?"true":"false");
    

    it return "true"

    0 讨论(0)
  • 2021-02-07 01:59

    Why redundant boolean

    Just use

    return  (usrname.equals(username) && passwd.equals(password));
    
    0 讨论(0)
  • 2021-02-07 01:59

    Java ternary operator is an expression, and is thus evaluated to a single value. As per the Javadocs, for below given expression

    result = someCondition ? value1 : value2;
    

    if the boolean condition is true then assign the value of value1 to the result, else assign value2 to the result. Both value1 and value2 should be of same value type.

    Hence the correct syntax of a return statement would be

    return boolean_condition ? value_when_true : value_when_false
    
    0 讨论(0)
  • 2021-02-07 02:10

    You can do

    return (usrname.equals(username) && passwd.equals(password) )?  true : false;
    

    true and false can be replaced by any return value you want. If it is just boolean then you can avoid ternary operator altogether. Just do

    return  (usrname.equals(username) && passwd.equals(password));
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题