0

Lets say I'm creating a person obj and prompted the user for fields sequentially:

Enter a Name: ......

Enter a Age: .....

Enter a Gender: ......

After I ask to enter a name I check if the name is valid, if not I ask for ONLY the name again. If the name is valid I then ask for the age while saving what the user entered for the name. Same thing for age, they enter an age if invalid only ask for the age again, if the age was valid save it then ask for the gender.

At the end I have all the fields and break out of lets say a while loop that contained all these prompts and create the obj.

Is there a way to sequentially check and prompt and save user input in this manner? I don't want to have to use nested while loops for each prompt

//psuedocode

while(true) {
   Console.WriteLine("What's your name")
   
   //read input from user 

   //error check it 

   //if valid store in name in variable

  //else prompt for name again

  Console.WriteLine("Whats your age?")
  
  //prompt user

  //if valid store it in age variable

  //else prompt age again ONLY

  //etc

 
  
}

if I were to use a continue statement whenever I get bad data it would reprompt for all prior prompts up until that point which is redundant behavior

0

1 Answer 1

2

Change the while loop to be around each question, rather than all questions, then use the continue keyword when they gave an acceptable response.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.