Calling a method from a switch - java

My issue is that I can't seem to call the "RustySword" block from a "switch" in my main class. See below.
import java.util.Scanner;
public class Heart {
static int playerGold = 100;
static int oldHatPrice = 25;
static int canOfBeansPrice = 250;
static int rustySwordPrice = 125;
public static Scanner Economy = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hi, Welcome to my store.\nWould you like to see my wares?");
String c = Economy.next();
switch (c) {
case "yes":
System.out.println("old hat: " + oldHatPrice +" gold\nRusty Sword: " + rustySwordPrice + " gold\nCan of beans: " + canOfBeansPrice + " gold");
String e =Economy.next();
switch (e) {
case "Rusty sword":
RustySword();
break;
default: System.out.println("I don't think you need that!");
}
}
}
public static void RustySword() {
System.out.println("Would you like to buy this rusty sword?\n Rusty sword: " + rustySwordPrice + "\n Your gold: " + playerGold);
String a = Economy.nextLine();
switch (a) {
case "yes":
if (playerGold >= rustySwordPrice) {
System.out.println("Here you go");
playerGold = playerGold - rustySwordPrice;
System.out.println("-Rusty Sword- added to inventory\n Gold remaining: " + playerGold);
}
else {
System.out.println("Sorry, you don't have enough gold!\ncome back when you have more.");}
break;
case "no":
System.out.println("Is there anything else I can do for you?");
String d = Economy.nextLine();
switch (d) {
case "no":
System.out.println("Thanks for shopping");
break;
}
break;
default: System.out.println("i'm not sure what your talking about!");
}
}
}

You are using next() to read the input that is reading only till space then the cursor is being placed in the same line after reading the input.
So the cursor will be at the end of the line \n if your input is only a single word e.g., yes in your case.
The end of the line will be consumed by following next() method. Hence your condition is not matching.
Use nextLine() to read the complete line and use it. You can look into this question
for more info.

Related

Prompting user with a print after each Switch-case except case: "0 exit"

Instead of making it blank each time the user is finished with a case, I've added a println("Next command?>") in the runCommandLoop method as a cheap solution to my problem. But that also means when case "0" or "exit" is choosen, "Next command?>" is printed out one last time BEFORE shutting down.
Simply put I want it to prompt after every case except "0 shutdown".
Calling the startup method is another option as well I guess but that doesn't make much difference either.
private void startup() {
System.out.println("\nCommand?>\n" + "1: register new dog\n" + "2: increase age\n" + "3: list dogs\n"
+ "4: remove dog\n" + "0: exit\n");
}
private void runCommandLoop() {
boolean done;
do {
String command = readCommand();
done = handleCommand(command);
System.out.println("\nNext command?>");
} while (!done);
}
private String readCommand() {
String command = input.registerString();
return command;
}
private boolean handleCommand(String command) {
switch (command) {
case "1":
case "register new dog":
dogList.registerDog();
break;
case "2":
case "increase age":
dogList.increaseAge();
break;
case "3":
case "list dogs":
dogList.listDogs();
break;
case "4":
case "remove dog":
dogList.removeDog();
break;
case "0":
case "exit":
return true;
default:
printMenu();
}
return false;
}
private void printMenu() {
System.out.println("Error: wrong command\n" + "The available commands are:\n" + "1: register new dog\n"
+ "2: increase age\n" + "3: list dogs\n" + "4: remove dog\n" + "0: exit");
return;
}
private void closeDown() {
System.out.println("Shutting down...");
input.closeInput();
}
private void run() {
startup();
runCommandLoop();
closeDown();
}
public static void main(String[] args) {
Interface startup = new Interface();
startup.run();
}
In case you need to see what the dogList methods do (the arraylist variable name is just temporary):
public void registerDog() {
String name = input.registerStringLoop("Name");
String breed = input.registerStringLoop("Breed");
int weight = input.registerIntPrompt("Weight");
int age = input.registerIntPrompt("Age");
Dog dog = new Dog(name, breed, age, weight);
doggoList.add(dog);
System.out.println(dog.getName() + " has been added to the register.\n" + dog.toString());
}
public void listDogs() {
if (doggoList.size() == 0) {
System.out.println("Error: no dogs found");
} else {
System.out.print("Smallest tail length to display?>");
int smallestTailLength = input.registerInt();
sortDogs();
if (smallestTailLength == 0) {
System.out.println(doggoList);
} else
for (Dog s : doggoList) {
if (s.getTailLength() >= smallestTailLength)
System.out.println(s);
}
}
}
public void increaseAge() {
System.out.print("Enter the name of the dog?>");
String dogName = input.registerString();
for (Dog s : doggoList) {
if (s.getName().equalsIgnoreCase(dogName)) {
s.increaseAge();
sortDogs();
System.out.println(s.getName() + " is now " + s.getAge() + " years old.");
return;
}
}
Thanks in advance.
It should be as simple as
if (!done){
System.out.println("\nNext command?>");
}

How to exit java method

Sorry for the poor title, i didn't know a better paraphrase..
Sooo i am currently writing a Grocery List program and i am stuck on my addItemsToList method. Basically i want it to have to 'exit' points. One of which will bring you back to the main menu of the application and one of which will bring you back to the context menu of that addItemsToList method.
Unfortunately i am completely stuck.
Here is my code for the method:
private static void addItemsToList(){
System.out.println("To which category do you want to add? ");
categoryInstructions();
int choice2 = scan.nextInt();
if(choice2 == 5){ // i am "getting out" here just fine
interact(); // this is the method that instructs everything to happen in the main method
}else {
System.out.println("What do you want to add? Type 'exit' for menu");
i = scan.next(); // this is where the second "exit" point is supposed to be if someone types "exit"
if (i.compareTo(exit) != 0) {
System.out.println("Please enter the quantity ");
int quant = scan.nextInt();
if (choice2 == 1) {
GrocerieList.foodstuffsList.add(i);
GrocerieList.foodstuffsAmount.add(quant);
} else if (choice2 == 2) {
GrocerieList.hygeneList.add(i);
GrocerieList.hygeneAmount.add(quant);
} else if (choice2 == 3) {
GrocerieList.drinkList.add(i);
GrocerieList.drinkAmount.add(quant);
} else if (choice2 == 4) {
GrocerieList.otherList.add(i);
GrocerieList.otherAmount.add(quant);
}
} else {
addItemsToList();
}
}
}
Just for a better understanding here is categoryInstructions():
public static void categoryInstructions(){
System.out.println("Press");
System.out.println(" ");
System.out.println("\t\t" + "(1)" + "\t--\t" + "for foodstuffs");
System.out.println("\t\t" + "(2)" + "\t--\t" + "for hygene");
System.out.println("\t\t" + "(3)" + "\t--\t" + "for drinks");
System.out.println("\t\t" + "(4)" + "\t--\t" + "for others");
System.out.println(" ");
System.out.println("\t\t" + "(5)" + "\t--\t" + "to get back main menu");
}
Now whats happening is that i can exit addItemsToList perfectly fine if choice2 == 5 but i cannot seem to find the logical solution fo exiting if i is equal to "exit". I got it to work quick and dirty with the application first asking for the quantity and then exiting but that isn't quite what i want.
Since i am (obviously) a beginner any other comments on my style or else would also be greatly appreciated!!
You could use a switch case for this purpose, a flag to know when to execute an elegant exit and a while loop to help you stay in the menu until a user provides the correct input.
For instance:
public class Controller {
private GroceriesController groceriesController;
private boolean isRunning; // our flag that will help us to quit the menu
public Controller(GroceriesController groceriesController) {
this.groceriesController = groceriesController;
}
public void run() {
isRunning = true;
while (isRunning) {
clearScreen();
displayLogo();
displayMainMenu();
handleMainMenu(); // method that will do all the job;
}
}
private void handleMainMenu() {
int userChoice = scanner.nextInt();
switch (userChoice) {
case 1:
groceriesController.handleGroceriesMenu();
break;
case 2:
returnItems();
break;
case 0:
isRunning = false; // exit from the menu
break;
default:
System.out.println("Invalid input");
break;
}
}
private void displayMainMenu() {
System.out.println("\n Grocery store:\n"
+ "[1] Buy stuff\n"
+ "[2] Return stuff\n"
+ "[0] Leave store");
}
}
public class GroceriesController {
private boolean isRunning; // same strategy as before
public void handleGroceriesMenu() {
isRunning = true;
while (isRunning) {
clearScreen();
displayLogo();
displayMenu();
handleMenu();
}
}
private void handleMenu() {
int userChoice = scanner.nextInt();
switch (userChoice) {
case 1:
addItemToCart(item);
System.out.println("The item: " + item + "has been added.");
break;
case 2:
removeItemFromCart(item);
System.out.println("The item: " + item + "has been removed.");
break;
case 0:
isRunning = false; // exit from the menu
break;
default:
System.out.println("Invalid input");
break;
}
}
private void displayMenu() {
System.out.println("\n Select:\n"
+ "[1] Buy item\n"
+ "[2] Put back\n"
+ "[0] Leave");
}
}
In this way, you can have multiple menus that are calling each other and at the end, the program finishes on its own, without wild return; or System.exit(0);
Edit: Added one more class for better insight.

How to fix my RockPaperScissors game written in Java?

I'm trying to write a RockPaperScissors game for my Java class but I'm having trouble with my code. When it runs, sometimes it outputs the wrong thing and sometimes it is correct.
For example when the user enters P the computer is either supposed to answer with Tie, My Point, or Your Point, and then under it will say what each of us played. But often it will say some thing like "Your Point!" "R beats R".
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tie = 0;
int win = 0;
int loss = 0;
String playerChoice;
System.out.println(RockPaperScissors.getComputerChoice());
while (true)
{
System.out.println();
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
playerChoice = input.nextLine();
if (playerChoice.equalsIgnoreCase("quit")) break;
else
//switch statement
if (playerChoice.equalsIgnoreCase(
RockPaperScissors.getComputerChoice()))
{
System.out.println("Tie!");
tie++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("R")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("P")))
{
System.out.println("Your Point!");
System.out.println(playerChoice + " beats "
+ RockPaperScissors.getComputerChoice());
win++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("P")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("")))
{
System.out.println("My Point!");
System.out.println(RockPaperScissors.getComputerChoice()
+ " beats " + playerChoice);
loss++;
}
else
{
System.out.println("Invalid Input!");
}
}
System.out.println();
System.out.println("You won " + win + " times.");
System.out.println("You lost " + loss + " times.");
System.out.println("We tied " + tie + " times.");
}
public static String getComputerChoice ()
{
int compChoiceInt;
String compChoice;
compChoiceInt = (int) (Math.random() * 3);
switch (compChoiceInt)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
default:
compChoice = "Invalid Input";
System.out.println("Invalid Input.");
break;
}
return compChoice;
}
You're calling getComputerChoice() many times in your code that decides if the user wins, loses, or ties. That can result in several different possible outcomes to each round because each one of those method calls results in a new choice being randomly generated. Instead of calling that method several times, declare a variable and call it just once, before you compare it to the player's choice.

JOptionPane run not working

I'm working on a program and I don't understand what's wrong with the program, I've tried to make it work, but every time I would run it and put in an answer, it adds a zero to the answer. Help.
import javax.swing.JOptionPane;
public class Furniture
{
public static void main(String args[])
{
String response_1 = JOptionPane.showInputDialog(null, "Type of Table - 1)Pine Wood, 2)Oak, 3)Mahogany");
int type_of_wood = Integer.parseInt(response_1);
String response_2 = JOptionPane.showInputDialog(null, "Size of table - 4)Small, or 5)Large");
int size = Integer.parseInt(response_2);
int price_of_wood = 0;
int price_of_table = 0;
switch(type_of_wood)
{
case 1:
price_of_wood = 100;
break;
case 2:
price_of_wood = 225;
break;
case 3:
price_of_wood = 310;
break;
case 4:
price_of_table = 0;
break;
case 5:
price_of_table = 35;
break;
default:
JOptionPane.showMessageDialog(null, "Unknown Number entered.");
}
JOptionPane.showMessageDialog(null, "The price is " + price_of_wood + price_of_table + " dollars");
}
}
When you use variable like int, float etc. with String in println() for showing output they gets concatenated instead of getting added or whatever operation you try to do. So first evaluate your expression which is to output. Try this,
int price = price_of_wood + price_of_table;
JOptionPane.showMessageDialog(null, "The price is " + price + " dollars");

How do I write a menu with a switch statement while using methods to perform each task

This program lets a user edit their string. I have problems with each method in the menu part of the program. For some reason they light up as an error, I'm using Eclispe. The rest of the code, besides the method definitions, works perfectly. I need to somehow define each task for the menu in a new method.
Each error says the exact same thing, this:
Multiple markers at this line
Syntax error, insert "[ ]" to complete Dimension
Syntax error, insert ";" to complete BlockStatements
Illegal modifier for parameter shortenSpace; only final is permitted
Syntax error on token "shortenSpace", AnnotationName expected after this
token
I have commented in the code where my errors appear.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AuthoringAssistant {
public static Scanner scnr;
public static void main(String[] args) {
userText();
printMenu();
}
/** Get user text*/
public static void userText() {
String userText;
System.out.println("Enter a sample text:");
userText = scnr.nextLine();
System.out.println("You entered: " + userText);
return;
}
/** Print Menu*/
public static void printMenu() {
String c = "c";
String w = "w";
String f = "f";
String r = "r";
String s = "s";
String q = "q";
String menuChoice;
String userText;
Scanner in = new Scanner(System.in);
System.out.println("");
System.out.println("MENU");
System.out.println(c + " - Number of non-whitespace characters"); /** This option counts the number of characters minus whitespace */
System.out.println(w + " - Number of words"); /** This option counts the number of words */
System.out.println(f + " - Find text"); /** This option finds a user specific in word in the text */
System.out.println(r + " - Replace all !'s"); /** This option replaces all exclamation points with a period */
System.out.println(s + " - Shorten spaces"); /** This option removes all whitespace that is larger than one space */
System.out.println(q + " - Quit"); /** This quits */
System.out.println("");
System.out.println("Choose an option: ");
menuChoice = scnr.next();
return;
switch (menuChoice) {
case "c": {
public static int getNumOfNonWSCharacters(); { /** ERROR */
// case "c": whitespace
String newStr = "";
newStr = userText.trim().replaceAll(" ","");
int lenInput = newStr.length();
System.out.println("Number of non-whitespace characters: " + lenInput);
return;
}
}
break;
case "w": {
public static int getNumOfWords(); { /** ERROR */
// case "w": number of words
userText = userText.replaceAll("\\s+", " ");
int counter = 0;
for (int i = 0; i <= userText.length()-1; i++) {
if (Character.isLetter(userText.charAt(i))) {
counter++;
for (i = 0; i <= userText.length()-1; i++) {
if(userText.charAt(i)==' ')
counter++;
}
}
}
System.out.println("Number of words: " + counter);
return;
}
}
break;
case "f": {
public static String findText(); { /** ERROR */
// case "f": find text
System.out.println("Enter a word or phrase to be found: ");
String find = scnr.next();
int matches = 0;
Matcher matcher = Pattern.compile(find, Pattern.CASE_INSENSITIVE).matcher(userText);
while (matcher.find()) matches++;
System.out.println("\"" + find + "\" instances: " + matches);
return;
}
}
break;
case "r": {
public static String replaceExclamation(); { /** ERROR */
// case "r": replace !'s
String userTextE = "";
userTextE = userText.replace('!', '.');
System.out.println("Edited text: " + userText);
return;
}
}
break;
case "s": {
public static String shortenSpace() { /** ERROR */
// case "s": shortens spaces
String userTextE = "";
userTextE = userText.replaceAll("\\s+", " ");
System.out.println("Edited text: " + userText);
return;
}
}
break;
case "q":
// case "q": quits
System.exit(0);
break;
return;
}
}
}
Am I supposed to have the printMenu method not contain the rest of the methods for the menu task?
You cannot define your method inside the body of the switch case. This is because,
Your code:
switch (menuChoice) {
case "c": {
public static int getNumOfNonWSCharacters(); { /** ERROR */
// case "c": whitespace
String newStr = "";
newStr = userText.trim().replaceAll(" ","");
int lenInput = newStr.length();
System.out.println("Number of non-whitespace characters: " + lenInput);
return;
}
}
break;
Has a method definition within a method, (nesting of method definitions) which is not right. (That is definition of getNumOfNonWSCharacters() is nested within the definition of printMenu() )
Here's what you should do:
Write a different java class which has the functionalities, say
Functionalities.
Each method of this class should carry out one of the
functionalities/ tasks for which you have written this program.
Then within the switch case, you create an object of the
Functionalities class, and call the corresponding method.
Also, I don't see why you are returning after : menuChoice = scnr.next(); .
Code after the return; will not execute, because the control returns back to the caller of this method.
Hope this helps.

Categories