• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get the program to start over?  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I am trying to create a user controlled exit at the end of my program. I have to make it if the users says yes then the program repeats and if the user says no or cancel then the program ends. I already know how to make the program end but I am not sure how to make it repeat. Here is my code



I need help with what I should put on line 33 in place of the placeholder text. Thanks in advanced.
 
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use a while loop to check if user selected to continue "yes" or not. If yes then loop continues else come out of it
 
Ranch Hand
Posts: 170
Hibernate Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inside your if statement with YES_OPTION, call main again. Skip other options of no and cancel as you are not doing anything there and there is nothing to execute after your option checks.
 
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't recommend calling main() again from within main(), thats not good practice (except in controlled recursion) as it can lead to a stack overflow crash.

As Tushar says put your repeating code in a loop. Think about which type of loop is best. Create a boolean flag eg. moreAccounts to control when the loop terminates. Once you have done this you should realise that you no longer need to call System.exit().
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the hardest things to learn is that more methods are better. They let you think about your program at more abstract levels. Let's say I had a program that needed to get user input, do some calculations, then print some output. At a very high level, it is easy to understand what each step does. So, I can write some methods, and (although this is not best practice) call each in order from main:


Now I want my program to repeat that if my user gives me the correct input. It's now pretty easy to see how i'd loop that code. All i need is a way to ask the user if they want to do it again:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!