好吧,例如,程序会询问用户输入,然后它会产生一些输出然后就完成了,但是如果用户想要通过main方法,如何让它再次循环呢?
这是我的代码:
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
}
如果用户再次决定,我将如何让它再次运行?
答案 0 :(得分:3)
String x=null;
Scanner sc = new Scanner(System. in );
String hisName=null;
do{
System.out.print("Please enter the first name of the person you would love to know about : ");
hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("y/n");
x=sc.next();
}while(x.equals("y"));
答案 1 :(得分:3)
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("AGAIN (Y/N) : "); // ask the input from user
String var= sc.next();
if(var.equalsIgnoreCase("Y")){// Matches "Y" or "y"
main(null); // if input is Y then call main again.
}
}
答案 2 :(得分:1)
boolean exit = false;
while(!exit){
Scanner sc = new Scanner(System. in );
System.out.print("Please enter 'exit' to exit or, the first name of the person you would love to know about : ");
String hisName = sc.next();
if(!"exit".equals(hisName)) {
printSomeInfoAbout(hisName);
}else{
exit = true;
}
}
答案 3 :(得分:0)
如果用户选择输入其他名称,则创建一个获取输入并调用它的方法
答案 4 :(得分:0)
一个简单的循环,它将检查用户将空字符串作为它将退出的第一个名称。
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
do {
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
if (hisName.equals("")) {
printSomeInfoAbout(hisName);
}
} while (!hisName.equals(""));
}
答案 5 :(得分:0)
请查看以下代码段,它可能对您有所帮助..
public static void main(String [] args){
String name;
Scanner scn = new Scanner(System.in);
boolean flag = false;
do {
System.out.println("Please enter the first name of the person you would love to know about : ");
name = scn.next();
System.out.println("Your friend " +name+ " is a great guy..!");
System.out.println();
System.out.println("Enter 1 to continue giving other" +
" names or Enter 2. to quit");
System.out.println();
int choice = scn.nextInt();
if( choice == 1 ) {
flag = true;
} else {
System.out.println("ThankU.. Bye");
flag = false;
}
} while(flag);
}