Right now, I'm writing a program that will allow a user to create an infinite number of exercise objects, and will only stop when the user input is equal to certain a value. Below is the relevant code:
String s = "";
do {
UserAddedExercise();
System.out.print("Do you want to add another exercise? (Y/N) ");
s = in.nextLine();
} while(s.equalsIgnoreCase("y"));
public static void UserAddedExercise() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the exercise name: ");
String exe = in.nextLine();
System.out.print("Enter the location for the exercise: ");
String loc = in.nextLine();
System.out.print("Enter if the exercise is weighted or not: ");
String w = in.nextLine();
System.out.print("Enter the the muscle location exercised: ");
String ml = in.nextLine();
Exercise e = new Exercise(exe,loc,w,ml);
}
The issue I'm encountering is that the UserAddedExercise()
method properly executes in the do-while loop, and the print statement is printed out, however the program automatically exits after the statement has been printed out, preventing user input. The exercise objects will later be added to an ExerciseSet ArrayList, but I want to get this solved first, and to understand WHY it is my program exits the do-while loop. Thank you.
CodePudding user response:
Adding to previous comments, try something like this:
public class MainClass{
static Scanner in;
public static void main(String[] args){
String s = "";
do
{
UserAddedExercise();
System.out.print("Do you want to add another exercise? (Y/N) ");
s = in.nextLine();
} while (s.equalsIgnoreCase("y"));
}
public static void UserAddedExercise(){
in = new Scanner(System.in);
System.out.print("Enter the exercise name: ");
String exe = in.nextLine();
System.out.print("Enter the location for the exercise: ");
String loc = in.nextLine();
System.out.print("Enter if the exercise is weighted or not: ");
String w = in.nextLine();
System.out.print("Enter the the muscle location exercised: ");
String ml = in.nextLine();
Exercise e = new Exercise(exe, loc, w, ml);
}
}
class Exercise{
public Exercise(String exe, String loc, String w, String ml){
}
}