This question already has answers here:
How do I compare strings in Java?
                                
                                    (23个答案)
                                
                        
                                6年前关闭。
            
                    
以下是我的Java代码块
我不能退出while块,在其他模块中运行相同的代码是完美的。请帮助我

public void current_ER(View v){
        try{
                String[] parameters= {uid};
                Caller c=new Caller();

                c.url="current_ER.php";
                c.parameters=parameters;
                c.join(); c.start();

                String result=MainActivity.result;
                System.out.print("before while");
                while(result=="START") {
                    try {
                          Thread.sleep(10);
                          System.out.print(result);
                    }
                    catch(Exception ex) {
                          ex.getLocalizedMessage();
                    System.out.print("in catch");
                    }
                }
                System.out.print("after while");
                Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
                {
                    System.out.print("before start indent block");
                    /////////to next screen////
                    Intent Manage_Expense=new Intent(this,Manage_Expense.class);
                    Manage_Expense.putExtra("er_details", result);
                    //MainActivity.result="START";
                    Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
                    //startActivity(Manage_Expense);
                }

}catch(Exception e){
                System.out.println(e.getMessage());

}

    };

最佳答案

首先,使用:

while("START".equals(result))


为了比较字符串。

主要错误是您从不更新result

首先,您设置:

String result=MainActivity.result;


因此resultMainActivity.result指向同一对象。
但是,在另一个线程中,您需要更新:

MainActivity.result=resp;


使MainActivity.result指向resp,但result仍指向先前的值。

如果要在循环中检查变量,则必须确保在循环内更改了该值。

关于java - while循环仍然没有异常出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20761486/

10-16 05:19