问题
I want to loop my program to repeat if the user inputs y the program will repeat over and over again ,but if the user finally inputs n the program will stop
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");
}
}
回答1:
I would separate the code into a separate function, and call that function if the scanner returns a "y". For example:
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();
}
}
Hope that helps
回答2:
Basically, you could use a do-while
loop...
do {
//...
System.out.println("Would you like to do it again?(Y/N)\n");
String repeat = sc.next();
} while (repeat.equalsIgnoreCase("y"));
See The while and do-while Statements for more details...
回答3:
Because, the question has to be asked once, it must be use do while statement to achieve what you are looking for.
Code:
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"));
}
来源:https://stackoverflow.com/questions/24543811/repetition-of-the-program