Java - JSONArray中的字符串在if语句中不匹配

问题描述:

我真的不明白我在哪里出错了。任何帮助将非常感激。Java - JSONArray中的字符串在if语句中不匹配

我有一个JSONArray

JSONArray jsonArray = new JSONArray(responseString); 

哪里responseString为[ “概率”, “2”]

我得到的第一个String

String maybeProb = jsonArray.getString(0); 

,当我告诉它使用吐司一切正常,吐司刚刚说出问题

Toast.makeText(getBaseContext(),maybeProb ,Toast.LENGTH_LONG).show(); 

但是,当我使用if (maybeProb == "prob")它不返回true

为什么不?我究竟做错了什么???

为大家介绍一些细节:形成原JSONArray来自一个HttpPost到我的服务器

InputStream is = null; 

HttpResponse response = httpclient.execute(httppost); 

HttpEntity entity = response.getEntity(); 

is = entity.getContent(); 

//Convert response to string 
responseString = convertStreamToString(is); 

public String convertStreamToString(InputStream inputStream) { 

    StringBuilder sb = null; 
    String result = null; 

    try 
    {   
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); 
     sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) 
     { 
     sb.append(line + "\n"); 
     } 

     inputStream.close(); 
     result = sb.toString(); 

    } 
     catch(Exception e) 
    { 
     Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show(); 
    } 

    // return the string 
    return result; 
} 

我的服务器上的PHP这使得响应

$message = array("prob", "2"); 

$response = json_encode($message); 

print($response); 

responseString

非常感谢任何能帮助我的人

在Java中使用的比较对象.equals()方法,而不是"=="操作

这一个将以下代码

if(maybeProb == "prob") { 
} 

if(maybeProb.equals("prob")) { 
} 
+0

而问题不在了。非常感谢,我对Java仍然很陌生。 – 365SplendidSuns

+0

@ user1165417很高兴听到它.. – Prabhakaran

等于运算符(==)返回true,只有当两个对象是相同的,如果没有他们的价值是一样的。因此,当您使用对象比较的对象。maybeProb"prob"返回false

如果你想要做比较,你必须使用maybeprob.equals("prob")