【问题标题】:How to call back to specific line of code in method?如何回调方法中的特定代码行?
【发布时间】:2020-03-26 21:58:24
【问题描述】:

我是编程新手,正在编写我的第一款游戏。我遇到的一个问题是我不知道如何跳转到不是方法的特定行或代码段。

    System.out.println("\n--------------------------------------------\n");
    System.out.println("Hello customer, what would you like to do today?");
    System.out.println("1: Buy");
    System.out.println("2: Sell");
    System.out.println("3: Leave");
    System.out.println("\n--------------------------------------------\n");

    choice = myScanner.nextInt();

    if (choice==1) {
        System.out.println("\n--------------------------------------------\n");
        System.out.println("What would you like to buy?");
        System.out.println("1: Chain Armor-500 Gold.");
        System.out.println("2: Gold Broadsword-200 Gold.");
        System.out.println("3: Nevermind.");
        System.out.println("\n--------------------------------------------\n");

        choice = myScanner.nextInt();

        if (choice==1) {

        }
        else if (choice==2) {

        }
        else if (choice==3) {

        } else {

        }

我想跳到运行 else 语句时询问他们想买什么的部分。

【问题讨论】:

  • 把它放在一个while循环中。

标签: java eclipse if-statement methods


【解决方案1】:

正如@JohannesKuhn 提到的,这可以使用while 循环来实现:

if (choice==1) {
    while(true) {
        System.out.println("\n--------------------------------------------\n");
        System.out.println("What would you like to buy?");
        System.out.println("1: Chain Armor-500 Gold.");
        System.out.println("2: Gold Broadsword-200 Gold.");
        System.out.println("3: Nevermind.");
        System.out.println("\n--------------------------------------------\n");

        choice = myScanner.nextInt();

        if (choice==1) {
        } else if (choice==2) {
        } else if (choice==3) {
        } else {
            continue; // Skips the rest of the code, returning to the start of the loop.
        }

        break; // Breaks out of the loop, "placing" you after it's closing bracket
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多