So basically I'm trying to make a minigame only using IF statements and in a single class, and everything is working smoothly so far. My biggest issue is, the "back" prompt. I tried system.exit(0), but since it kills the program, that won't be an answer. my question is, how do you "re-run" the class? For instance, when you are in the "options" menu, how do you go back in the main menu?
import java.util.Scanner;
public class Main {
public static void main (String[]args)
{
//Main Menu Prompt.
System.out.println ("Welcome to my mini parkour game!");
System.out.println ("Decide which trick to use, and don't mess up!");
System.out.println ("Choose one: Play, Quit");
Scanner bruh = new Scanner (System.in);
String MainMenu = bruh.nextLine ();
// Quit Prompt.
if (MainMenu.equals ("Quit"))
{
System.out.println ("You have quit the game.");
System.exit (0);
}
// Play Prompt.
if (MainMenu.equals ("Play"))
{
System.out.println ("Proceed to level 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
Scanner playgame = new Scanner (System.in);
String LevelSelect = playgame.nextLine ();
if (LevelSelect.equals ("1"))
{ System.out.println("You have reached this block of code!");
}
}
//code block to remind that java is case sensitive.
else {
System.out.println("error, try picking one again. (case sensitive.)");
return new Main();
}
}
}
I wanted the output to be at the main menu prompt even when you are from the play prompt, without killing the program.
I believe a while loop controlled by your user input stored in a variable will do the magic. You will have to learn how to use while loops.
If you want to advance to a God-level Java programmer use enum where you define your states and then create inside while loop a state machine using switch-case.
I am too lazy to type a working code here from my phone but something like that on a high level:
enum State { PLAY, QUIT };
public static void main(String[] args) {
boolean runAgain=true;
State state;
while (runAgain) {
//get the input from user
//update state
switch(state) {
case PLAY :
// update state
break;
case QUIT:
// update STATE
break;
//case WHATEVERELSE...
default:
assert false : "never get here";
}
}
}
It is a bit of learning and reading java specs involved, but Hey, after doing that you'll be able to program a working algorithm for .... an ELEVATOR!
Good luck!
Related
Why does the code break when the default case of the switch function is used.
import java.util.Scanner;
public class Main {
static void checkCommand(String command)
{
switch (command) {
case "add" -> System.out.println("added");
case "access" -> System.out.println("accessed");
case "compare" -> System.out.println("compared");
default -> {
System.out.println("Invalid command, please try again");
enterCommand();
}
}
}
static void enterCommand(){
System.out.print(">>> ");
Scanner usrInput = new Scanner(System.in);
String input = usrInput.nextLine();
while (!input.equals("quit")){
checkCommand(input);
System.out.print(">>> ");
input = usrInput.nextLine();
}
}
public static void main(String[] args) {
enterCommand();
}
}
When I enter in "add", "compare", or "access", and then "quit", the program works as intended, but if I enter in anything that is incorrect where it uses the default case, the program breaks and repeatedly asks for input even if the input is "quit". I have tried a few different things to fix it and nothing has worked. I'm trying to keep the switch statement but if there isn't a way to keep it and have the program run as intended I am open to other options.
Your code works for me. The only problem is that I have to enter quit twice, after entering an invalid command, in order for the program to terminate.
Here is output from a sample run of the exact same code as in your question:
>>> access
accessed
>>> add
added
>>> george
Invalid command, please try again
>>> compare
compared
>>> quit
>>> quit
I am required to enter quit twice because method enterCommand is being called from method checkCommand. You don't need to do this. The while loop, in method enterCommand will ensure that the user is prompted again to enter a command – even after [s]he has entered an invalid command.
Calling enterCommand from checkCommand means that you are essentially calling enterCommand recursively. In the above output, I needed to enter quit twice, since I only entered a single, invalid command. I suggest that you run your code in a debugger to understand why you get this behavior.
As #OldDogProgrammer wrote in his comment to your question, you should create a Scanner object only once rather than each time method enterCommand executes.
As #MadProgrammer wrote in his comment, a do-while loop may be more appropriate than a plain while loop.
Also, quit is not an invalid command so I think that you need to handle that command in method checkCommand and the handling is that you just ignore the command. Since you are using switch expressions, I couldn't find a way to "ignore" a case so in the below code I simply print an empty string. Alternatively, you could print an appropriate message such as Good bye, for example.
import java.util.Scanner;
public class Main {
private static Scanner usrInput;
static void checkCommand(String command) {
switch (command) {
case "add" -> System.out.println("added");
case "access" -> System.out.println("accessed");
case "compare" -> System.out.println("compared");
case "quit" -> System.out.print("");
default -> {
System.out.println("Invalid command, please try again");
}
}
}
static void enterCommand() {
String input;
do {
System.out.print(">>> ");
input = usrInput.nextLine();
checkCommand(input);
} while (!input.equals("quit"));
}
public static void main(String[] args) {
usrInput = new Scanner(System.in);
enterCommand();
}
}
Here is the output when I ran the above code:
>>> access
accessed
>>> add
added
>>> George
Invalid command, please try again
>>> compare
compared
>>> quit
As you can see, I only need to enter quit once.
You need to understand the recursive mechanism.
When the latest recursive has done, it needs to do the remaining tasks from previous recursive. I added comments into your code to explain:
static void checkCommand(String command){
switch (command) {
// ...
default: {
System.out.println("Invalid command, please try again");
enterCommand(); // recursive is calling here.
}
}
}
static void enterCommand(){
System.out.print(">>> ");
Scanner usrInput = new Scanner(System.in);
String input = usrInput.nextLine(); // time 1: input: test | time 2: input: quit -> done recursive 1.
while (!input.equals("quit")){
checkCommand(input); // time 1: go to default and call recursive, go to input time 2
System.out.print(">>> "); // Do the remaining task from time 1. In case you input time 3: "quit". the program will exit.
input = usrInput.nextLine();
}
}
The more recursives are called, the more remain tasks need to do. In your code, to quit the program, you need to type "quit" (n + 1) times if the recursive is called n times
Solutions: To quit immediately after typing "quit" in the first time, just remove the recursive call.
default: {
System.out.println("Invalid command, please try again");
}
//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}
So I've seen a bunch of other posts about this, but they didn't apply since a) I'm trying to return to the main method while SKIPPING a while loop inside of the main. I'm making a text adventure game and it works in steps (separate methods), by calling the next step from within the step at the end. for example, the first step is EastStoryline1(), and the second is EastStoryline2(), and at the end of the code for EastStoryline1(), it says "EastStoryline2()".
So the actual main is pretty small, since it's just one method looping into the next. There are also 2 while loops in the main. The first comes right after I establish the scanner and boolean playagain, which basically surrounds the rest of the main starts the game while playagain = true. the second loop comes right after the first, which basically says while def (the players health) > 0, play the events of the game. After the second loop, but still in the first loop, the code calls the method Die(), and then asks the player whether they want to play the game.
SO basically, what code do I put inside Die() in order to break out of any existing loop chain and bring it to the next code after Die() is called in the main. The problem is that I also use Die() in other methods, and each time it's called I want it to return to the code after Die() in the main. Here's the code for the main (sorry for bad formatting):
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
boolean playagain = true;
while(playagain == true)
{
while(def > 0)
{
TitleScreen("TXT ADVENTURE!");
System.out.println("Pick a character: Rogue, Paladin, or Priest
(capitals DO matter!)");
String character = keyboard.next();
CharacterChoice(character);
System.out.println("You wake up on a dusty road, with no memory of who
you are or how you got here. You can only remember your name, and how to
fight. To the east lies a small dock with a boat. To the west, there seems
to be a sand-scarred mountain range. Do you go east, or west?");
String ew = keyboard.next();
EastWest(ew);
}
Die();
System.out.println("Do you want to play again?");
String playornah = keyboard.next();
if(playornah.equals("yes") || playornah.equals("Yes"))
{
playagain = true;
}
else
{
playagain = false;
}
}
}
And this was the code for Die I used system.exit(0), but now I want it to return to the main after Die is called there instead of just ending the program):
public static void Die()
{
System.out.println("GAME OVER");
System.exit(0); //I tried using break but it wouldn't compile
}
So what to I code in Die() in order for (no matter where it's called) return to the main after the spot where Die() is called.
public static void Die()
{
System.out.println("GAME OVER");
System.exit(0); //I tried using break but it wouldn't compile
}
System.exit(0); ends the program. If you want to just end the method either:
Let the method end naturally when it has no more statements. (Just remove System.exit(0);)
Replace System.exit(0); with a return; statement
From the docs:
A method returns to the code that invoked it when it
completes all the statements in the method,
reaches a return statement, or
throws an exception (covered later),
whichever occurs first.
You can't return from an external method, How ever you can use a try-finally to return it once you have run your code.
I have written the following code in the main function of my program to generate a menu driven program. There are basically six options available on the Menu and the menu() not only displays the menu but also returns the user's choice. If you require the code for that, I'll post it.
public static void main(String args[])throws IOException
{ BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object=new attendance_and_student_management();
int flag=1;
while(flag==1)
{ int var=object.menu();
if(var==1)
{ System.out.println("\f");
object.add_student();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());
}
else if(var==2)
{ System.out.println("\f");
object.search_student();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());
}
else if(var==3)
{ System.out.println("\f");
object.change_student_information();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==4)
{ System.out.println("\f");
object.take_attendance();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==5)
{ System.out.println("\f");
object.attendance_summary();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==6)
{
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==7)
{ System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
}
else
{ System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int chhh=Integer.parseInt(bw.readLine());
if(chhh==1)
{ flag=1;
}
else
{ flag=0;
}
}
}
}
Now I am facing only one issue with this code, it goes to a particular method and remains stuck on that method forever. So for instance, I want to add a student. On the menu, I choose 1 and since var==1 is true, the method add_student is called. Once I am done adding a student, I AM NOT ABLE to come back to the menu. What I mean by this is that the line
System.out.println("Would you like to return to the Main Menu to perform more tasks....."); is not executed. What is the Flaw?
My goal is to first display the menu through the menu function, then ask the user if he/she wants to perform any more tasks. If he/she wants to, then by pressing 'Y' the menu should get displayed again and so on. If after any iteration the user wants to quit then he/she should either choose 7 as an option to quit or simply enter 'N' or any other valid character.
PS: This is my new attempt at the code, I decided to change the switch statement as I do not fully understand it.
When I am running a simple java program in eclipse, when I run it, the console flashes what it should, then it disappears.
public class apples {
public static void main(String[] args) {
int age = 60;
if (age < 50) {
System.out.println("You are young");
} else {
System.out.println("You are old");
}
}
}
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen.
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen. One possibility is to use
while(true);
to stop the application from exiting. Beware that you should only use this for debugging methods!
Another, probably better, way is to ask for input before closing the window.
Simply read a line from standard input. Your program will wait until you type something and only then exit.
Scanner sc = new Scanner(System.in); // create a scanner that will read from standard input
String s = sc.nextLine(); // You don't even need to save the return value of
// sc.nextLine() here