Java - Send user back to the start? - java

How will I go about restarting the app if the user asks so.
Here is my code:
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
}
else if (restart != 1){
System.out.println("Goodbye..");
}
so if user press 1, the app restarts.. How can i create this?

Your application sounds like a loop, so lets use one.
/* #return true if should restart */
boolean run() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
return true;
}
else if (restart != 1){
System.out.println("Goodbye..");
return false;
}
}
while (run());
But this is Java, so you might as well do it more object oriented.
public class MyRestartable {
private boolean shouldRestart = true;
public void run() {
while(this.shouldRestart) {
start();
}
System.out.println("Goodbye..");
}
boolean start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
this.shouldRestart = sc.nextInt();
}
}

Oh the joys of object based programming.
void start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
***start();***
}
else if (restart != 1){
System.out.println("Goodbye..");
}

Use a while loop, and at the point you want to send the user back to the beginning, use the break; command enclosed in an if statement to decide whether the user is sent back or continues.

A simple while loop would work.
public static void Loop(){
Scanner input = new Scanner(System.in);
int loop = 1;
while(loop == 1){
System.out.println("Would you like to restart?");
System.out.println("Press 1 = yes");
System.out.println("Press 2 = no");
loop = input.nextInt();
}
}

Related

How do I use loop statement instead of go to statement

while(true)
{
switch (...)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
System.out.println("(1)Continue (2)Exit");
//example:
int choice = scanner.nextInt();
if (choice == 1)
continue; //it should go to switch
else if (choice == 2)
{
System.out.println("Exit..."); // should exit
break;
}
else
{
System.out.println("Wrong num, try it again!"); // should ask choose again until we enter 1 or 2
//goto example;
}
}
My problem is: It goes to the beginning of the loop when I choose the wrong number. I want it to go to the part where the choose is asked (int choice = scanner.nextInt();) and asking again. "1" - > switch, "2" - > "exit" , "3" - > ask choice again.
Try like the below
while(true)
{
int choice = scanner.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
//goto example;
}
}
This should solve your problem.
import java.util.Scanner;
class Main
{
private static void switcher(int key)
{
switch (key)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
switcher(0);//replace with whatever you need
System.out.println("(1)Continue (2)Exit");
while(true)
{
int choice = sc.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
}
switcher(0);//replace with whatever you need
}
}
}
If you have other requirements, please update your question.
You can try doing something like this, maybe a little ugly but I think it will work:
function get_choice(choice) {
if (choice == 1) {
// do something
} else if (choice == 2) {
// do something else
} else {
// something else
}
}
and then you just do something like get_choice(1);
try this approach:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int choice;
do {
System.out.println("Enter your choice :");
System.out.println("1. Start program");
System.out.println("2. End program");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
} while (choice != 2);
System.out.println("Exit application :");
}
}

wrong value in while statement java

Fairly new to coding but I am struggling to find the issue in my code. It is just a class which will run a few other classes and ask if you want to play again or not.
The issue is when you choose the first game and then say n or no to not play again when you play a second game after answering that you would like to play again it goes back to asking what game you would play instead of repeating the game.
public static void arcade() {
Scanner scanner2 = new Scanner(System.in);
String choice;
int game;
boolean finish;
finish = false;
game = 0;
do {
try {
System.out.println(
"Which game would you like to play? \n1. Coin toss\n2. Rock Paper Scissors \n3. Number Game\n4. Exit");
game = scanner2.nextInt();
switch (game) {
case 1:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
coinToss(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
choice = scanner2.next();
}
} while (finish != true);
break;
case 2:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
rockPaperScissors(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 3:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
numberGame(scanner2);
System.out.println("Would you like to play again?");
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 4:
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid selection");
}
} catch (java.util.InputMismatchException e) {
System.err.println("Please use numbers");
scanner2.nextLine();
}
} while (game != 4);
scanner2.close();
}
Your forgot to re-initialize every time the finish variable to false:
case 2:
choice = "yes";
do {
finish = false;
...
You should do it for every case. Consider also that in your 3rd switch you also forgot to scan for the input after asking "Would you like to play again?".
Finally try to refactor your code a bit :)

How to return to main menu when exit is inputted

I want to return to main menu aka "eventSelection" if 4 (exit) is selected. Right now I have it as return which exits whole program.
import java.util.*;
public class SchedulingProgram {
public static void main (String [] args) {
eventSelection();
}
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit = 4. \nINPUT : ");
int actionSelect = sc.nextInt();
if (actionSelect >= 1 && actionSelect <= 4) {
if (actionSelect == 1) {
addEvent();
} else if (actionSelect == 2) {
displayEvent();
} else if (actionSelect == 3) {
printAlert();
} else if (actionSelect == 4) {
return;
}
} else {
System.out.println("Error : Choice " + actionSelect + " Does Not Exist.");
}
}
I used to play with these kind of things too when I first started learning Java.
The most simple solution is indeed a while-loop. It evaluates the boolean expression and keeps executing the code within its brackets for as long as the boolean equals 'true'.
I refactored your example:
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
int actionSelect = 0;
while (actionSelect != 4) {
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit program = 4. \nINPUT : ");
actionSelect = sc.nextInt();
switch (actionSelect) {
case 1:
addEvent();
break;
case 2:
displayEvent();
break;
case 3:
printAlert();
break;
default:
break;
}
}
System.out.println("Exited program");
}
It will now display your menu everytime a number is entered. Except when they enter 4, which now becomes the exit out of your entire program.
When faced with multiple if-else, it's perhaps better to use a switch-case. It takes a parameter and per case, you can define the action.
If the entered parameter doesn't match a case, it falls back to the default (in this case, it does nothing and the program will continue, showing the select menu anyway)
The 'break' keyword is needed to contain the cases. Otherwise, the next line of code would be executed as well. A bit more information about the switch statement can be found here.
And ofcourse, here's the link to the while-loops.
One last tip... As I learned to program, I found that there's nothing more important than to (re)search as much as I could on Google. There are examples aplenty out there.

by pass do while loop

I wondering is it possible to skip past a do while loop or even exit a method halfway through it if certain conditions are met?
Heres an example of what I mean ( everything works in this )
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
boolean bookExists = false;
boolean memberIDExists = false;
boolean memberCurrentlyLoaningBook = false;
int memberID = 0;
System.out.println("You must be a member of the library to loan out a book");
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
memberID = input.nextInt();
for (int i = 0; i < members.size(); i++) {
if (memberID == members.get(i).getMemberID()) {
memberIDExists=true;
if(members.get(i).isCurrentlyLoaningBook()==false){
successful = true;
memberCurrentlyLoaningBook=true;
}
}
}
if(!memberCurrentlyLoaningBook){
System.out.println("This member is currently loaning a book");
}
if (!memberIDExists) {
System.out.println("This member ID does not exist");
}
} while (successful == false);
EDIT
do while loops that are in the same method
do { these other do while loops are after this first one and do other things
} while (); ( I haven't included what they do as it takes up too
do { much space)
} while();
I have an option here to exit to the main menu, but i also have a do while loop after this, so whenever I enter 9 it just exits the current to while loop and goes on to the next one, is there anyway that I can skip past all the proceeding do while loops after I press 9, or even exit the method?
In your case continueor breakcould be useful. But if you want to exit the method you could just do it with return.
Try this, I have added break; when user enter "9" as an input. It will then come out of the do while loop.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
break;
}
EDIT:
Yes to Check for the next loop, add a condition with that loop
loop(your original condition && !successful)
{
}
EDIT 2:
TO come out of the loop and avoid other do while loops in the method, you can just return;
It will take back the control of the program through which this method was called.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
return;
}

Error handling with strings java

I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}

Categories

Resources