0

可能重复:
如何比较 Java 中的字符串?

我正在开发一个小程序,该程序使用Scanner. 如果您输入空白字符串,那么我希望控制台显示一条消息。

这是我尝试做的事情:

import java.util.Scanner; 
public class Adventure
{  
    public static void main(String[] args) 
    {      
        Scanner myScan = new Scanner (System.in);                             
        System.out.println("What's your name?");                                 
        String name = myScan.nextLine();

        while (!(name == ""))   //Always returns false.
        {
            System.out.println("That's not your name. Please try again.");
            name = myScan.nextLine();
        }

        System.out.println("It's a pleasure to meet you, " + name + ".");
    }
}

代码永远不会进入 while 循环。为什么?

4

1 回答 1

12

Change your condition to:

while(!name.equals("")) {

or as suggested below by m0skit0:

while(!name.isEmpty()) {

See also

于 2013-02-04T21:35:33.557 回答