Search code examples
javaloopsmethodsreturn

Java - Method to loop until a Y or N is entered


I have looked around and haven't found any questions that has been directly answered for my problem, if i'm wrong, sorry. I'm writing a program that is supposed to take in your birth information, year, month, day, hour, minute and then ask if they would like to do it again but using a method and loop until a Y/N is entered.

My problem is im not able to get the method to take in the Y/N and end the program, as well as end when a N is entered.

I think there is supposed a while or some sort of loop that needs to be in the method but im having a hard time figuring that out.

All my other methods work except for this one, any help would be appreciated, thanks.

This is the code I have for my method now:

public static boolean getYNConfirm(Scanner pipe, String prompt)
{

  String choice="";

  System.out.println(prompt);

        choice = pipe.nextLine();

        if(choice.equalsIgnoreCase("Y"))
        {
           return true;
        }
        else
        {
            return false;    
        }


}

And this is the code for my main program:

public static void main(String[] args) 
{
    int year, month, day, hour, minutes;
    String msg="";
    boolean done = false;
    Scanner in = new Scanner(System.in);

   while(!done)
   {

   year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);

   month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
   switch (month)
   {
      case 1:
      msg = "January";
      break;  
      case 2:
      msg = "February";
      break;
      case 3:
      msg = "March";
      break;
      case 4:
      msg = "April";
      break;
      case 5:
      msg = "May";
      break;
      case 6:
      msg = "June";
      break;
      case 7:
      msg = "July";
      break;
      case 8:
      msg = "August";
      break;
      case 9:
      msg = "Septemeber";
      break;
      case 10:
      msg = "October";
      break;
      case 11:
      msg = "November";
      break;
      case 12:
      msg = "December";
      break;         
   }

   hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
   minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);

   System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");


   SafeInput.getYNConfirm(in, "Would you like to play again?");

   }
}

}

Thanks for any help.


Solution

  • Value of done is always false. Change on last line:

    done = SafeInput.getYNConfirm(in, "Would you like to play again?");
    

    EDIT:

    Your logic does not fit if you return true Change here too:

    if(choice.equalsIgnoreCase("Y"))
            {
               return false;
            }
            else
            {
                return true;    
            }