'Can I call the loop methods from outside main function?
import java.util.Scanner; // needed for Scanner Class
public class MyClass
{
public static void main(String[] args)
{
boolean running = true;
GAME:
{
// Create a Scanner object for choice input.
Scanner console = new Scanner(System.in);
String gameName = "The Path";
PATHCHOICES:
while (running)
{
System.out.println("Enter your choice: Left, Right, or Run Away");
String choice = console.nextLine();
//make the do-while statement
do
{
if (choice.equals("Left"))
{
System.out.println("You choose to take the left fork in the road.");
break PATHCHOICES;
}
else if (choice.equals("Right"))
{
System.out.println("You choose to take the right fork in the road.");
break PATHCHOICES;
}
else if (choice.equals("Run Away"))
{
System.out.println("You choose to turn back and return the way you came.");
break PATHCHOICES;
}
else
{
System.out.println("please choose Left, Right, or Run Away");
choice = console.nextLine();
}
} while (choice != "Left" && choice != "Right" && choice != "Run Away");
}
DOORCHOICES:
while (running)
{
System.out.println("Enter your choice: Open The Door, Walk Away From The Door");
String choice = console.nextLine();
do
{
if (choice.equals("Open The Door"))
{
System.out.println("You open the door and walk into the next room.");
break DOORCHOICES;
}
else if (choice.equals("Walk Away From The Door"))
{
System.out.println("You walk away from the door and head back the way you came.");
break DOORCHOICES;
}
else
{
System.out.println("Open the door or Walk Away From The Door");
choice = console.nextLine();
}
} while (choice != "Open The Door" && choice != "Walk Away From The Door");
}
}
System.out.println("tacos");
}
}
Is it possible for me to call these loops methods into play without having to repeatedly type them out (copy paste)? I would like to be able to call the loops from outside the main GAME function if that’s possible. That way I don’t have to copy paste, copy paste, copy paste every time I want to use that same loop. I have both loops named PATHCHOICES AND DOORCHOICES, so if it is possible what syntax would I use?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
