Can I call the loop methods from outside main function? - java

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?

Yes, it's possible to create methods, in addition to many other improvements you could make. Here's a solution with methods and some improvements.
To start, here's a new method named "promptForDoor" which:
Lines 2-3: define a few strings that you're going to re-use
Line 5: start a loop here, simple "while", repeat forever
Line 6: print the input options (using strings defined from 2-3); also, use "print()" instead of "println()"
Line 9: check if their input matches with the string from Line 2, and use "equalsIgnoreCase()" since it doesn't matter what the user types in ("OPEN THE DOOR" or "open the door" should both work)
Line 10-11: print something informative, then eject from the method altogether by returning "choice"; this also ends the loop
Line 13-15: same logic as 9-11
Line 17: if you make it here, it's because you didn't match on Lines 9 or 13, so just repeat the whole loop again (including the prompt to the user, and reading input)
1 private static String promptForDoor(Scanner scanner) {
2 String openTheDoor = "Open the door";
3 String walkAwayFromTheDoor = "walk away from the door";
4
5 while (true) {
6 System.out.print(openTheDoor + ", or " + walkAwayFromTheDoor + "? ");
7 String choice = scanner.nextLine();
8
9 if (choice.equalsIgnoreCase(openTheDoor)) {
10 System.out.println("You open the door and walk into the next room.");
11 return choice;
12
13 } else if (choice.equalsIgnoreCase(walkAwayFromTheDoor)) {
14 System.out.println("You walk away from the door and head back the way you came.");
15 return choice;
16 }
17 }
18 }
Here's another method to prompt for path, it's the same structure as the other method.
1 private static String promptForPath(Scanner scanner) {
2 String left = "left";
3 String right = "right";
4 String runAway = "run away";
5
6 while (true) {
7 System.out.print(left + ", " + right + ", or " + runAway + "? ");
8 String choice = scanner.nextLine();
9
10 if (choice.equalsIgnoreCase(left)) {
11 System.out.println("You choose to take the left fork in the road.");
12 return choice;
13
14 } else if (choice.equalsIgnoreCase(right)) {
15 System.out.println("You choose to take the right fork in the road.");
16 return choice;
17
18 } else if (choice.equalsIgnoreCase(runAway)) {
19 System.out.println("You choose to turn back and return the way you came.");
20 return choice;
21 }
22 }
23 }
Here's an example to run it:
Scanner scanner = new Scanner(System.in);
String path = promptForPath(scanner);
String door = promptForDoor(scanner);
System.out.println("path: " + path);
System.out.println("door: " + door);
Along with sample input+output – including an uppercase input ("LEFT") which works fine, and an unexpected input ("jjjjj") which resulted in re-prompting the user to enter something valid. Finally, it printed out each of the inputs captured from the user ("LEFT" and "walk away from the door").
left, right, or run away? LEFT
You choose to take the left fork in the road.
Open the door, or walk away from the door? jjjjj
Open the door, or walk away from the door? walk away from the door
You walk away from the door and head back the way you came.
path: LEFT
door: walk away from the door

Related

Having issues with a program that skips the If Else part of the code

I am creating a text-based game and, so far, I have gotten the if and the else statements to work. However, the else if does not work. I've gone through several sites and several pages and even talked with a fellow coder. I've done what I can, such as replacing == with "?".equals(Call#)) then changing to Call#.equals("?"). I had the else if as a nested if but that also failed.
public static void FirstRoom(){
System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
System.out.println("\n ----- \n");
Scanner console = new Scanner(System.in);
String Call = console.next();
if (Call.equals("Inspect")) {
System.out.println("\nYou can only see darkness");
System.out.println("\n ----- \n");
} else if(Call.equals("Light Lantern")){
System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
System.out.println("\n ----- \n");
}else{
System.out.println("\nWhat do you mean?");
System.out.println("\n ----- \n");
FirstRoom();
}
String Call2 = console.next();
if(Call.equals("Inspect")) {
System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
System.out.println("\n ----- \n");
}
}
When I type in Light Lantern, I expect it to say You pull the lighter from your pocket and, turning the knob, raise the lantern's wick and light it. Instead, it skips to the second statement (supposed to also wait for you to input for the second) and says You see a large sword to your right and a bag to your left. There is a door in front of you and a door behind.
Inspect
You can only see
darkness
Light Lantern
You see a large sword to your
right and a bag to your left.
There is a door in front
of you and a door behind.
You need to use console.nextLine() not console.next()
String Call /*bad name*/ = console.next();
Will only take the first word "Light"
String call = console.nextLine(); //using normal JAVA naming conventions
Will take everything up to the the end of line character which means you will be able to input multiple words like "Light Lantern"
For more information on the difference between next() and nextLine() you can check out this post
You are stopping to take input at String Call2 = console.next(); before checking if Call is equal to "Inspect". You should be checking Call2.
This would be my suggestion to reworking that method:
public static void FirstRoom() {
System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
System.out.println("\n ----- \n");
Scanner console = new Scanner(System.in);
String Call;
boolean exitRoom = false;
boolean lantern = false;
while(!exitRoom) {
Call = console.nextLine();
if(Call.equals("Inspect") && !lantern) {
System.out.println("\nYou can only see darkness");
System.out.println("\n ----- \n");
} else if(Call.equals("Light Lantern")) {
System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
System.out.println("\n ----- \n");
lantern = true;
} else if(Call.equals("Inspect") && lantern) {
System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
System.out.println("\n ----- \n");
} else if(Call.equals("Leave")) {
System.out.println("You leave the room");
System.out.println("\n ----- \n");
exitRoom = true;
} else {
System.out.println("\nWhat do you mean?");
System.out.println("\n ----- \n");
FirstRoom();
}
}
}
When a command to leave the room is requested, the while loop ends.

Java Nested If statement-Or Compared to !=

I wasn't sure how to give a title for this problem, but basically this is part of my blackjack program. Also, since I did not know how to title this, I wasn't sure how to look it up, which is why I am asking here. So I am saying that when the user enters either 1 or 11 for the ace value, if they enter something other than 1 or 11, it asks the user again to put in 1 or 11. In my program everything works fine except when the user enters 1, then it just asks the question again. The program should only asks again if the input is not equal to 1 or 11. Here is my code as I made sure it always gives an ace for testing purposes:
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1=="A"){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
if ((1|11)!=(player_ace_selection)){
System.out.println("Please enter a 1 or 11: ");
int new_selection=input_var.nextInt();
total=total + new_selection;
}
else {
total=total + player_ace_selection;
}
}
System.out.println(total);
Thanks in advance.
The expression (1|11) uses binary OR, which produces 11:
11 = 01001
1 = 00001
(11|1) = 01001
Hence, the comparison is the same as 11!=player_ace_selection
You should change the code to use logical OR, i.e.
if (1!=player_ace_selection && 11!=player_ace_selection) {
...
}
In addition, you need to fix card1 == "A" comparison for card1.equals("A")
Instead of an If statement, try a while loop. A while loop ensures that your program waits for your user to pick the right answer. You also made a mistake with your logical operations. The correct way to use "OR" in this context is to compare your user input to both '1' and '11' separately using '||'.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
while(player_ace_selection != 1 && player_ace_selection != 11){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
player_ace_selection = input_var.nextInt();
}
total += player_ace_selection;
}
System.out.println(total);
There are some problems in your code, please consider this example and compare it with yours.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){ // compare the content not the reference (==)
System.out.println("Do you want a 1 or 11 for the Ace?: ");
try{ // wrap with try-catch block
int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input
if ((player_ace_selection!=1)&&(player_ace_selection!=11)){
System.out.println("Please enter a 1 or 11: ");
try{
int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input
total=total + new_selection;
}catch(NumberFormatException e){
// do something to catch the error
}
}
else {
total=total + player_ace_selection;
}
}catch(NumberFormatException e){
// do something to catch the error
}
System.out.println(total);
}

Java - if statement keeps looping

I'm having a little problem with getting my if statement to work. The scenario is that the user should be able enter 1 if they want British teams or 2 if they want American teams. Once they pick a region a list of teams will appear and they enter the number of team and the information of that team should print out but for some reason it just keeps looping and asks to enter a team. I have simplified my code slightly for here otherwise it would be too big.
ArrayList<STeam> teams = rCSV.readSTeams("sports-teams.csv");
Scanner UInput = new Scanner(System.in);
System.out.println("Enter 1 for British teams or 2 for American teams");
int choice = UInput.nextInt();
for (STeams st1 : teams) {
if (choice == 1) {
System.out.println("Choose: 1. London FC");
int choice2 = UInput.nextInt();
{
if (choice2 == 1) {
if (st1.getName().equals("London FC")) {
System.out.println(st1);
}
}
}
}
else if (choice == 2) {
System.out.println("test");
}
}
Apologies if this is extremely messy.
I have a separate class that reads the file and a separate class for the sports teams and I know these work as I have done something similar like this but with only using 1 if statement within another instead of 2.
choice is never updated in your for loop.
You probably want to do:
for (STeams st1 : teams) {
int choice = UInput.nextInt();
if(choice == 1) {
// ...
}
Hey Looks like you are running loop without any condition. So it will run till there are tokens in your teams. You need to use break once you are done with your selection.
You are using this for (STeams st1: teams) which might be a left over code. Since it has no brackets the for will continuously loop over this.
EDIT: Ok, you probably want something like this:
ArrayList britishTeams = rCSV.readSTeams("sports-teams.csv");
Scanner UInput = new Scanner(System.in);
System.out.println("Enter 1 for British teams or 2 for American teams");
int choice = UInput.nextInt();
if (choice == 1)
{
for(int option = 0; option<britishTeams.size; option++)
System.out.println("Option " + option + ": " + britishTeams.get(option).name);
int choice2 = UInput.nextInt();
System.out.println("You chose: " + britishTeams.get(choice2).name);
}
To add the american team, DONT copy/paste this all over again, make the code that takes a list of teams and chooses one a method ;-)

Console Calculator error java

So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.

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