In: Computer Science
How do I go back to the start of the main method with the given code?
Hello I am making this java program and there is a point in the code where if the user types the character y it will start the program back at the beginning of the main method.
How can I do this without drastically changing the code?
For instance, if I type y, the program will go back to line 1 and repeat the entire process until I press n for no.
public static void main(String[] args) {
Scanner scnr = new
Scanner(System.in);
System.out.println("Welcome to
schedule generator!");
System.out.println("How many
classes would you like to take?");
boolean validInput = false;
int userInput =
scnr.nextInt();
while(!validInput) {
if(userInput
<= 0 || userInput >= 6) {
System.out.println("Please choose between 0 and 6 classes.");
System.out.println("How many classes would you like to
take?");
userInput =
scnr.nextInt();
}
else
if(userInput >= 1 && userInput <= 5) {
validInput = true;
System.out.println(":)");
}
}
System.out.println("Would you like
to generate another schedule? y - yes, n - no");
String
userResponse = scnr.next();
if(userResponse.equals("y")) {
//FixME
}
else
if(userResponse.equals("n")) {
System.out.println("Goodbye");
}else
{
System.out.println("Goodbye");
}
}
}
Create a while loop contains flag variable interchange with 1 or 0 based on the requirement. Done.
import java.util.*;
class Main{
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int flag=1;
while(flag==1){
System.out.println("Welcome to schedule generator!");
System.out.println("How many classes would you like to
take?");
boolean validInput = false;
int userInput = scnr.nextInt();
while(!validInput) {
if(userInput <= 0 || userInput >= 6) {
System.out.println("Please choose between 0 and 6 classes.");
System.out.println("How many classes would you like to
take?");
userInput = scnr.nextInt();
}
else if(userInput >= 1 && userInput <= 5) {
validInput = true;
System.out.println(":)");
}
}
System.out.println("Would you like to generate another schedule? y
- yes, n - no");
String userResponse = scnr.next();
if(userResponse.equals("y")) {
flag=1;
}
else if(userResponse.equals("n")) {
flag=0;
System.out.println("Goodbye");
}else {
flag=0;
System.out.println("Goodbye");
}
}
}
}