-2
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

4 回答 4

0
while(name.isEmpty()){
    System.out.print("Enter a name: ");
name=input.nextLine();
}
于 2013-04-09T15:47:35.947 回答
0

你也可以试试

while ((name = input.nextLine()).length() > 0)  
{  
   . . .   
}  
于 2013-04-09T15:49:59.110 回答
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 );
        }
    }

}
于 2013-04-09T15:45:37.187 回答
0

您可以检查 name.length() <= 0 是否可以退出。

于 2013-04-09T15:46:41.630 回答