从交换机调用方法

时间:2018-01-31 04:11:19

标签: java switch-statement

我的问题是我似乎无法从主类中的“开关”调用“RustySword”块。见下文。

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!");
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您正在使用next()读取只读取到空格的输入,然后在读取输入后将光标放在同一行中。

因此,如果您的输入只是一个单词,例如\n,则光标将位于行yes的末尾。

将通过以下next()方法使用该行的结尾。因此,您的情况不匹配。

使用nextLine()阅读完整的行并使用它。您可以查看此question 了解更多信息。