相同的代码在不同的系统打印不同的结果,
在windows xp下运行打印“bbb”字符串;在linux中运行打印“aaa”字符串。
代码如下,求解释
package pkg15;import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;public class treeTest { public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Tree Test");
shell.setSize(300, 300);
shell.setLayout(new FillLayout()); Text text = new Text(shell, SWT.BOLD);
text.setText("");
String string = text.getText();
System.out.println(string); if (string != "") {
System.out.println("aaa");
} else {
System.out.println("bbb");
} shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose(); }}

解决方案 »

  1.   


     if (string != "") {
                System.out.println("aaa");
            } else {
                System.out.println("bbb");
            }
    中string !=""改成 string.equals(""),即可。
    java中字符串比较不要用“==”“!=”
      

  2.   


    一个是在linux下,一个是在windows下
      

  3.   


    你说的这点我知道的,
    但是我要问的不是你说的这样,在windows下 (   string !="" )能够编译和运行通过
    我想问题应该是两个操作系统编译会编译成不同的汇编,从而结论不同,
    所有现在想要知道是不是这个?
      

  4.   

    而且我也试了一下 直接赋值字符串为空的话,输出的是“bbb”
      

  5.   

    ==和equals()的区别大体上是比较值和比较地址。
    那就跟两个系统的寻址实现有关,当然机器代码是不一样的。
    java中用==或!=来比较字符串本来就是不可取的,所以造成以上差异也是正常的。
      

  6.   


    现在我的问题不是 == 与 equals()的区别,它们的区别现在不考虑
    而是同一份代码不同系统中的区别,现在是 (!=)在windows中能够通过这个前提下来问的
      

  7.   

            text.setText("123");
            String string = text.getText();
            System.out.println(string);        if (string != "123") {
    改成这样看看是否还有差异~
      

  8.   

    已测试如果字符串不为空,windows和linux中结果是一样的,都取if中得结果如果字符串为空,windows中取else中得结果,linux取if中得结果
      

  9.   

    另外已测试直接给字符串赋值空串(String string="";不是获取文本框的值),两系统中结果是一样的,都取else中得结果,也就是能用           
     if (string != "")
    这个判断
      

  10.   

    或许windows中所有""字符串都指向同一个地址
      

  11.   

    text.getText()其实主要要看这个方法怎么实现