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”,请问这是为什么啊?
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”,请问这是为什么啊?
两个字符串 之间比较 如果是 == 号 那么比较的是 内存中的地址
你要想比较内容 应该 用 equals() 方法 equals 比较的是内容你可以 将 a=="0" 改写为 a.equals("0")
a.equals("0");
判别对象的内容相等一般用equals方法,基本数据类型才可以使用==
== 是比较两个对象的内存地址的
在此程序中 显然 a=="0" 永远不能返回true
前面String a=new String(); 改为 int a=0;
再把a=in.readLine(); 改为a=Integer.parseInt(in.readLine());
最后再把if(a=="0"): 改成if(a==0)就可以了
如果用string的话就应该用equals去判断了.
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.equals("0")) //改为equals
System.out.println("为0");
else
System.out.println("不为0"); }
}凑个热闹
对于基本数据类型,比较的是数据的值,例如 int a=11;int b=11;c=12;
boolean istrueAB=(a==b);
boolean istrueAC=(a==c);
结果: istrueAB=true;istrueAC=flase;
对于引用数据类型,比较的是对象的引用值(既对象在内存中的地址),例如
String a=new String("aaa");
String b=a;
String c=new String("aaa");
boolean istrueAB=(a==b);
boolean istrueAC=(a==c);
结果:istrueAB=true;istrueAC=flase;
因为a和b指向同一块内存,所以引用本身的值是 相等(即第一个new String("aaa")的内存地 址)而第二个new String("aaa")是另一个内存 地址.
"equals()"的使用:该方法用来比较两个引用变量所引用的对象的内容是否相等
例如: String a=new String("aaa");
String b=a;
String c=new String("aaa");
boolean istrueAB=(a.equals(b));
boolean istrueAC=(a.equals(c));
结果:istrueAB=true;istrueAC=true;
有些专业语言说的不够准确,见谅,希望对你有帮助