How to use this boolean in an if statement?

前端 未结 8 1538
一个人的身影
一个人的身影 2020-11-28 15:35
private String getWhoozitYs(){
    StringBuffer sb = new StringBuffer();
    boolean stop = generator.nextBoolean();
    if(stop = true)
    {
        sb.append(\"y\         


        
相关标签:
8条回答
  • 2020-11-28 16:15

    Since stop is boolean you can change that part to:

    //...
    if(stop) // Or to: if (stop == true)
    {
       sb.append("y");
       getWhoozitYs();
    }
    return sb.toString();
    //...
    
    0 讨论(0)
  • 2020-11-28 16:15

    Try this:-

    private String getWhoozitYs(){
        StringBuffer sb = new StringBuffer();
        boolean stop = generator.nextBoolean();
        if(stop)
        {
            sb.append("y");
            getWhoozitYs();
        }
        return sb.toString();
    }
    
    0 讨论(0)
  • 2020-11-28 16:19

    additionally you can just write

    if(stop)
    {
            sb.append("y");
            getWhoozitYs();
    }
    
    0 讨论(0)
  • 2020-11-28 16:27

    = is for assignment

    write

    if(stop){
       //your code
    }
    

    or

    if(stop == true){
       //your code
    }
    
    0 讨论(0)
  • 2020-11-28 16:28

    The problem here is

    if (stop = true) is an assignation not a comparision.

    Try if (stop == true)

    Also take a look to the Top Ten Errors Java Programmers Make.

    0 讨论(0)
  • 2020-11-28 16:32

    if(stop = true) should be if(stop == true), or simply (better!) if(stop).

    This is actually a good opportunity to see a reason to why always use if(something) if you want to see if it's true instead of writing if(something == true) (bad style!).

    By doing stop = true then you are assigning true to stop and not comparing.

    So why the code below the if statement executed?

    See the JLS - 15.26. Assignment Operators:

    At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

    So because you wrote stop = true, then you're satisfying the if condition.

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