日期:2014-05-20  浏览次数:20660 次

请教一下关于String类的赋值问题
import   java.io.*;
class   test
{
public   static   void   main(String[]   args)
{
String[]   s=new   String[5];
System.out.println(s[0]);
InputStreamReader   ir;
BufferedReader   in;
String   a=new   String();
try
{
ir=new   InputStreamReader(System.in);
in=new   BufferedReader(ir);
a=in.readLine();
}
catch(IOException   e)
{
System.out.println(e);
}

if(a== "0 ")
System.out.println( "为0 ");
else
System.out.println( "不为0 ");

}
}

代码如上
结果我运行的时候,输入了0,结果他居然显示出“不为0”,请问这是为什么啊?

------解决方案--------------------
要用a.equals( "0 ")

------解决方案--------------------

两个字符串 之间比较 如果是 == 号 那么比较的是 内存中的地址
你要想比较内容 应该 用 equals() 方法 equals 比较的是内容

你可以 将 a== "0 " 改写为 a.equals( "0 ")