• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to add a prompt to ask the user if they want to run the program again?  RSS feed

 
Karen Barlow
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I was wondering how to add a prompt to ask the user if they want to run the program again. And then continue prompting for input, computing and displaying results until the user says that they do not want to run the program again. Apparently this can be done however I want, but I must use a String to signal the end of the program.

So far my program looks like the following:




I'm not sure what or where to add to prompt the user again, I believe I am to use another while loop?... All I know, is if they don't want to continue then I can end program System.exit (0);
Any insight would be greatly appreciated.
 
Knute Snortum
Sheriff
Posts: 4087
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can wrap your code in a while loop, if the user might not want to answer the questions at all, or in a do/while loop, if the user needs to answer the questions at least once. Prompt for "end" to end the program, then test the input for "end" in the while part. Then just let the program "fall off the end." No reason to use System.exit();
 
Campbell Ritchie
Marshal
Posts: 55786
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't. If you start adding more loops you will make that code into a right mess. You need separate methods rather than trying to squeeze a lot of code into the main method. It is likely that the first method will have a loop which calls another method and then asks for input as to whether you want to run again. That method would therefore contain about 4 or 5 lines of code.

Remember there is a kind of loop which always runs once and then considers whether to run again.

Why are you calling nextLine in line 25? That is only necessary if followed by another nextLine call.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To take Campbell's advice a little further...

Imagine if you had a method you called that did just about everything. I.e. your main looked something like:

public static void main(String[] args){
runProgram(); //this may need to take some arguments...
}

now answering your question is easy. you write a loop that calls that single method and asks if they want to run it again. You break out of your loop depending on what they input.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!