How do I restart a program in Java? [duplicate] - java

This question already has answers here:
How would I use a while loop to keep requesting user input
(3 answers)
Closed 2 years ago.
I have looked at other StackOverflow questions on this topic but being a new developer I am extremely confused. I am trying to write a program that asks the user riddles and restarts after the user gets three wrong answers on one specific riddle. The code that needs the restart is:
if (wrongAnswer == 3){
System.out.println("You have failed three times.");
restartApp();
The code where I need to restart should go right where the restartApp() is right now.
Thanks in advance!

So, as Turing85 mentioned, restarting the whole program probably isn't the way to go. Generally, you use what's called a state machine. For this example, a simple one can be implemented with a while loop. Here's an example:
import java.util.Scanner;
public class foo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("enter a value, enter -1 to exit...");
int value = scan.nextInt();
if(value == -1){
System.out.println("exiting");
break;
}else{
System.out.println("do stuff with the value");
}
}
}
}
and here's the output:
enter a value, enter -1 to exit...
1
do stuff with the value
enter a value, enter -1 to exit...
2
do stuff with the value
enter a value, enter -1 to exit...
4
do stuff with the value
enter a value, enter -1 to exit...
-1
exiting

Related

I need to get my Java program to start back at the beginning after an invalid input

I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message

Java: How do I get a Scanner object to ignore unwanted/invalid inputs? [duplicate]

This question already has answers here:
Scanner input validation in while loop
(3 answers)
Closed 5 years ago.
I am trying to set up a simple text tree that reads in either single-characters (y/n) or integers that correspond to a printed list (1-4). I want to know the easiest way to have the program ignore user inputs that don't correspond to the given options like so:
import java.util.Scanner;
public class simpleMenu
{
Scanner sc = new Scanner(System.in);
String choicePick;
public static void main(String[] args)
{
System.out.println("Would you like to continue? (y/n)");
choicePick = sc.next();
if(choicePick.equals("y"))
{
// The program continues.
}
else if(choicePick.equals("n"))
{
// The program closes.
}
else
{
/*
The scanner ignores the input, ideally without having to restate the question.
The program does not quit or move on until "y" or "n" is entered.
*/
}
}
}
Bonus points if you can help me implement a 'back' option that takes me to the previous choice.
While the next string is not Y or N sc.next() until it is. Then use that string.

Keep on prompting user after invalid input

Now I know that there is a thread called "Validating input using java.util.Scanner". I already looked there and that thread only answered 1/2 of my problems. The other half is when someone enters a number greater than 2 I get Array Index Out of Bounds Exception. I just need help on if someone enters a 3 for either row or column, the console should prompt something like this:
"Enter the coordinates to place an 'X'. Row then Column."
//enters 3 and 3
"Please enter a valid input"
It would keep and asking the user for a valid number until he gives one.
Would I need to do something like the !keyboard.hasNextInt() but for integers? And that would run smoothly with the rest of my code?
You could use a do-while loop. Something like
do {
//prompt
//input
} while (input not valid);
Where prompt and input should be replaced by code to prompt the user and accept input. In the while section, check if input is valid.
You're question isn't too clear but I'll try to make sense of it.
I'm assuming you've named your scanner "keyboard"
Before I try running this code, the first problem I can see is this (Note that I grabbed this from your code before you edited the question):
while (board[row][col] != ' ')
{
System.out.println("Already occupied space");
System.out.println("Choose again");
row = keyboard.nextInt();
col = keyboard.nextInt();
}
Earlier, you made sure that the user enters integers. However, you have abandoned that completely in this case.
Assuming you're trying to avoid an error if the user enters something other than an integer, this is what I would do:
while(true){
boolean valid = true;
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
row = keyboard.nextInt();
}
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
col = keyboard.nextInt();
}
if (valid && (row > 2 || col > 2)){
System.out.println("Please enter a valid input");
continue;
}
else if(!valid){
System.out.println("Please enter a valid input");
continue;
}
else
break;
}
There are a couple reasons this code might seem a bit long. First off, we're trying to test if the input is an integer before we attempt to store it as an int. Secondly, we want to compare the input after we store it successfully to see if it's less than 3. If the input isn't an integer, the boolean "valid" will be false. The way a compiler works, if valid is false in the if statement it will ignore anything to the right of the &&, avoiding an error.
I admit, this is using some commands that I haven't learned before, so this might not be the most efficient way. But you get the idea :)
P.S. You should probably throw the above code into a method.

java, getting user input through scanner and system.in [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
how can I give a condition on an input from "system.in" that will halt the program until the right value is inserted?
for exemple, I'm waiting for an INT from the user, 1,2,3,4 or 5
the user inputs "hello"
how can i give the user a message of "Invalid input, try again"
and keep the program at halt until he does give the right one?
update: I didnt came so you can write my code, right now it looks something like this:
int j=UserIn.nextInt();
switch (j) {
case 1:
break;
case 2:
writetoDic(word, "dict.txt");
break;
case 3:
word = correction;
break;
i'm asking that, if im getiing something else than an int from the user, how can i ask the user to give a valid argument instead of just getting an error?
You need to use a loop. I don't think you actually mean halt the program, but actually preventing to program to proceed until valid input. You can do something like this
Scanner scanner = new Scanner(System.in);
int num;
while (true) {
try {
System.out.println("Enter a number: ");
num = scanner.nextInt();
if (num >= 1 && num <= 5) {
break;
}
} catch (InputMistmatchException ex){
System.err.println("Input needs to be a number between 1 and 5, dummy.");
}
}
Program will run if not between 1 and 5 and not an integer

Java: User Input - Scanner - Program Hangs After Second Input

I'm making a console-based game of black jack that prompts the user asking him/her if he/she wants to: 'h' for hit, 's' for stay, or 'q' for quit. I'm using the Scanner class to receive input from the user in a while loop. The code works the first time it prompts the user and receives input, but it never works the second time. After the second prompt comes up, no matter what the user types, the program just waits and does nothing even though it's still running. I've been trying to get this to work for hours and have read the Java Docs, many SO questions, etc. Here's the relevant code:
public void gameloop() {
while (thedeck.cards.size() >= 1) {
prompt();
}
}
public void prompt() {
String command = "";
Boolean invalid = true;
System.out.println("Enter a command - h for hit, s for stay, q for quit: ");
Scanner scanner = new Scanner(System.in);
while (invalid) {
if (scanner.hasNext()) {
command = scanner.next();
if (command.trim().equals("h")) {
deal();
invalid = false;
} else if (command.trim().equals("s")) {
dealerturn();
invalid = false;
} else if (command.trim().equals("q")) {
invalid = false;
System.exit(0);
} else {
System.out.println("Invalid input");
scanner.next();
}
}
}
scanner.close();
}
Here's what the code outputs:
Dealer has shuffled the deck.
Dealer deals the cards.
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Enter a command - h for hit, s for stay, q for quit:
h
Dealer deals you a card:
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Queen of Hearts: 10
Enter a command - h for hit, s for stay, q for quit:
h (Program just stops here, you can keep entering characters,
but it does nothing even though the code is still running)
Any idea as to what's going wrong would be greatly appreciated. I also realize the while loop is a little ugly, but I just want to get this program in working condition before I start to revamp any code.
From the documentation for Scanner.close:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Here you close your scanner, and this causes System.In to be closed, which means you can't read any more input:
scanner.close();
It is better to open the scanner once and reuse it. Close it only when are sure you have finished reading all input, or are closing your application.

Categories

Resources