-1

I just want to loop this code until a proper answer in entered, can someone please teach me how to do so?

    //enter marital status
    {Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter your Marital Status folowing the numbers given");
    System.out.println("0 = Single");
    System.out.println("1 = Married Filing Jointly or Qualifying Widow(er)");
    System.out.println("2 = Married Filing Seperately");
    System.out.println("3 = Head of Household");
    status = keyboard.nextInt();

    {
        if (status == 0) {
        System.out.println("You have selected single.");}
    else if (status == 1) {System.out.println("You have selected Married Filing Seperately or Qualifying Widoe(er).");}
    else if (status == 2) {System.out.println("You have selected Married Filing Seperatey");}
    else if (status == 3) {System.out.println("You have selected Head of Household");}
    else if (status > 3) {System.out.println("Invalid selection"); System.exit(0);}
    }

1 Answers1

-1

You can simply:

boolean valid = false;
while(!valid) {
    System.out.println("Please enter your Marital Status folowing the numbers given");
    System.out.println("0 = Single");
    System.out.println("1 = Married Filing Jointly or Qualifying Widow(er)");
    System.out.println("2 = Married Filing Seperately");
    System.out.println("3 = Head of Household");
    status = keyboard.nextInt();

    if(status >= 0 && status <= 3) {
        valid = true;
    else 
        System.out.println("Invalid selection");
}

String response = "You have selected: ";
    switch(status){
        case 0:
            response += "single";
        break;

        case 1:
            response += "Married Filing Seperately or Qualifying Widoe(er).";
        break;

        case 2:
            response += "Married Filing Seperatey";
        break;

        case 3:
            response += "You have selected Head of Household";
        break;
    }

System.out.println(response);
P3Ri
  • 102
  • 4