【问题标题】:Comparing the value of readline() to a string [duplicate]将 readline() 的值与字符串进行比较 [重复]
【发布时间】:2015-08-14 01:26:49
【问题描述】:

我正在使用readline() 方法读取inputstream,然后尝试比较它。

代码如下:

//socket is defined before this
InputStream is = socket.getInputStream();

br = new BufferedReader(new InputStreamReader(is));

Line = br.readLine();

    if (Line  == "hey") {
        Log.d("watsapp client tag", "message pushed !!");
        Log.d("watsapp client tag", "" + Line);


    }
   else {

        Log.d("watsapp client tag", "message not pushed");
        Log.d("watsapp client tag", "" + Line);

    }

上面的代码总是执行 else 部分。虽然输入流的第一个值是“嘿”而第二个不是。所以我期待在logcat中“消息推送!!”和“未推送消息”相反,我得到了“未推送消息”

05-31 14:46:14.309    6138-6151/? D/watsapp client tag﹕ message not pushed
05-31 14:46:14.309    6138-6151/? D/watsapp client tag﹕ hey
05-31 14:46:14.339    6138-6151/? D/watsapp client tag﹕ message not pushed
05-31 14:46:14.339    6138-6151/? D/watsapp client tag﹕ <Messageadded:1112/>

请告诉if (Line == "hey") 行出了什么问题。谢谢!

【问题讨论】:

  • 比较字符串时使用equals

标签: java string sockets inputstream


【解决方案1】:

您必须使用equals() 方法比较String== 运算符在这里检查参考。像这样比较String(和其他引用类型变量) -

String firstString = "someValue";
String secondString = "someValue";

if(firstString.equals(secondString)){
   System.out.println("both string are equals"); 
}else{
   System.out.println("not equals"); 
}  

更新:有时我们会将String 类型的变量与String 文字或常量进行比较。那么最好像这样执行检查 -

String str1 = "aString";
String str2 = null;
System.out.println( "aString".equals(str1) ); //true;
System.out.println( "aString".equals(str2) ); //false;  

像这样比较的优势是在第二种情况下你永远不会得到NullPointerException

【讨论】:

  • 我试过了,然后它给了我 NPE
  • 好吧它现在工作了......谢谢
猜你喜欢
  • 1970-01-01
  • 2021-07-10
  • 2011-10-19
  • 2012-11-27
  • 1970-01-01
  • 2015-11-15
  • 2016-07-08
  • 2014-11-08
  • 1970-01-01
相关资源
最近更新 更多