简体   繁体   English

从开关调用方法

[英]Calling a method from a switch

My issue is that I can't seem to call the "RustySword" block from a "switch" in my main class. 我的问题是我似乎无法从主类的“开关”中调用“ RustySword”块。 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. 您正在使用next()来读取输入,该输入仅读取直到空格,然后在读取输入后将光标放置在同一行中。

So the cursor will be at the end of the line \\n if your input is only a single word eg, yes in your case. 因此,如果您的输入仅为单个单词,则光标将位于\\n行的末尾,例如,在您的情况下为yes

The end of the line will be consumed by following next() method. 行的结尾将通过以下next()方法使用。 Hence your condition is not matching. 因此,您的条件不匹配。

Use nextLine() to read the complete line and use it. 使用nextLine()读取完整的行并使用它。 You can look into this question for more info. 您可以查看此问题以获取更多信息。

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

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