我想循环我的程序重复如果用户输入y程序会一遍又一遍地重复,但如果用户最后输入n,程序将停止
import java.util.Scanner;
public class ReverseIt {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String name;
System.out.println("Input Name");
name = sc.nextLine();
StringBuilder rev = new StringBuilder(name);
System.out.println("NAME: "+name+"\n");
System.out.println("REVERSE:" +rev.reverse()+"\n");
System.out.println("Would you like to do it again?(Y/N)\n");
char repeat;
repeat = sc.next().charAt(0);
if(repeat == 'n'){
System.out.println("Program Stopped");
}
while(repeat == 'y'){
System.out.println("Input Name");
name = sc.nextLine();
System.out.println("NAME: "+name+"\n");
System.out.println("REVERSE:" +rev.reverse()+"\n");
System.out.println("Would you like to do it again?(Y/N)\n");
}
}
答案 0 :(得分:2)
我会将代码分成单独的函数,如果扫描程序返回" y"则调用该函数。例如:
public static void main(String[] args) {
function();
}
public static void function(){
Scanner sc = new Scanner (System.in);
String name;
System.out.println("Input Name");
name = sc.nextLine();
StringBuilder rev = new StringBuilder(name);
System.out.println("NAME: "+name+"\n");
System.out.println("REVERSE:" +rev.reverse()+"\n");
System.out.println("Would you like to do it again?(Y/N)\n");
char repeat;
repeat = sc.next().charAt(0);
if(repeat == 'n'){
System.out.println("Program Stopped");
}
if(repeat == 'y'){
function();
}
}
希望有所帮助
答案 1 :(得分:2)
基本上,您可以使用do-while
循环...
do {
//...
System.out.println("Would you like to do it again?(Y/N)\n");
String repeat = sc.next();
} while (repeat.equalsIgnoreCase("y"));
有关详细信息,请参阅The while and do-while Statements ...
答案 2 :(得分:0)
因为,问题必须要问一次,必须使用do while语句来实现你想要的。
代码:
public static void main(String... args) {
String name,finish;
do{
System.out.println("Input Name");
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
StringBuilder rev = new StringBuilder(name);
System.out.println("NAME: " + name + "\n");
System.out.println("REVERSE:" + rev.reverse() + "\n");
System.out.println("Would you like to do it again?(Y/N)\n");
finish = sc.next();
}while(finish.equalsIgnoreCase("Y"));
}