0

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!");
            }
        }
    }
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
  • 1
    Please use `nextLine` in all cases https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – OneCricketeer Jan 31 '18 at 04:15
  • 1
    Try `print`ing the value of `e` before your `switch` statement. Also, consider using `if` tests here; I don't see any reason to use `switch` in the first place. – Elliott Frisch Jan 31 '18 at 04:16

1 Answers1

0

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.

Sagar Pudi
  • 4,040
  • 3
  • 30
  • 51