应该有用的程序,但事实并非如此

时间:2013-08-29 00:02:08

标签: java string variables if-statement joptionpane

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;


public class Example {

    public static void main(String[] args) {

        String name;

        name = JOptionPane.showInputDialog(null, "ENTER TEST BELOW:"," ",3 );

        if (name == "TEST") {

            JOptionPane.showMessageDialog(null, "Welcome " + name + ", It works "," ",  1, new ImageIcon("Pictures/Example.jpg"));

        }

        else {

            JOptionPane.showMessageDialog(null,"Welcome " + name + ", It doesn't work."," ",  1, new ImageIcon("Pictures/Example.jpg"));

        }
    }

}

1 个答案:

答案 0 :(得分:2)

而不是将字符串与此进行比较:

name == "TEST"

你应该用这个:

name.equals("TEST")

A famous question解释了您需要执行此操作的原因。基本上,==会比较name"TEST"是否是同一个对象。它们不是同一个对象,但它们具有相同的内容,并且equals测试相同的内容。