首页 > 解决方案 > 如何回调方法中的特定代码行?

问题描述

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

    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 语句时询问他们想购买什么的部分。

标签: javaeclipseif-statementmethods

解决方案


正如@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
    }
}

推荐阅读