繁体   English   中英

从开关调用方法

[英]Calling a method from a switch

我的问题是我似乎无法从主类的“开关”中调用“ 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!");
            }
        }
    }

您正在使用next()来读取输入,该输入仅读取直到空格,然后在读取输入后将光标放置在同一行中。

因此,如果您的输入仅为单个单词,则光标将位于\\n行的末尾,例如,在您的情况下为yes

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

使用nextLine()读取完整的行并使用它。 您可以查看此问题以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM