如何继续循环,直到用户点击“输入”而不先输入名称

时间:2013-04-09 15:42:45

标签: java

import java.util.Scanner;
class lab5c
{
public static void main (String args[])
{
String name;
Scanner input=new Scanner(System.in);
System.out.print("Enter a name: ");
name=input.nextLine();

if (name.startsWith( "Liyana" ) || name.startsWith( "Batrisyia" ) || name.startsWith( "Arfa" )  )
System.out.println( "Ms. "+name );
else
System.out.println( "Mr. "+name );

}
} 

如何继续循环程序,直到用户点击“输入”而不先输入名称。

4 个答案:

答案 0 :(得分:0)

您可以检查字符串是否为空,如下所示:

public static void main (String args[]){
    String name = "default";
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a name: ");
    while(!name.isEmpty()){
        name=input.nextLine();

        if (name.startsWith( "Liyana" ) || name.startsWith( "Batrisyia" ) || name.startsWith( "Arfa" )  ){
            System.out.println( "Ms. "+name );
        }else{
            System.out.println( "Mr. "+name );
        }
    }

}

答案 1 :(得分:0)

您可以检查name.length()< = 0,然后退出。

答案 2 :(得分:0)

while(name.isEmpty()){
    System.out.print("Enter a name: ");
name=input.nextLine();
}

答案 3 :(得分:0)

您也可以尝试

while ((name = input.nextLine()).length() > 0)  
{  
   . . .   
}