Альтернатива на какое-то время l oop? - PullRequest
1 голос
/ 31 марта 2020
   private static void execute(Cheese[] cheeses) {
        int choice;  
        System.out.println("\n\nNow displaying the cheeses");
        choice = getChoice();
        while (true) {
            if (choice == 1)
                sortByName(cheeses);
            else if (choice == 2)
                sortByCost(cheeses);
            else if (choice == 3)
                sortByAge(cheeses);
            else if (choice == 4)
                System.exit(0);
            else
                System.out.print("Invalid entry - please reenter.");
            choice = getChoice();
        }
    }

По сути, я ищу альтернативу этому l oop. Я думал о том, чтобы сделать do l oop со строкой ввода, но мне трудно печатать ее. Есть ли способ получить do l oop, который ничего не делает или запрашивает ввод?

1 Ответ

2 голосов
/ 31 марта 2020

Вы пропускаете break в каждом состоянии. Чтобы продемонстрировать это, я звонил execute() пять раз, используя al oop. Чтобы смоделировать вызов различных опций, я сгенерировал choice случайно.

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Call#" + i);
            execute();
            System.out.println();
        }
    }

    private static void execute() {
        int choice;
        choice = getChoice();
        while (true) {
            System.out.println("Choice: " + choice);
            if (choice == 1) {
                System.out.println("sortByName");
                break;
            } else if (choice == 2) {
                System.out.println("sortByCost");
                break;
            } else if (choice == 3) {
                System.out.println("sortByAge");
                break;
            } else if (choice == 4) {
                System.out.println("Goodbye!");
                break;
            } else {
                System.out.println("Invalid entry - please reenter.");
                choice = getChoice();
            }
        }
    }

    static int getChoice() {
        return new Random().nextInt(10);
    }
}

Пример прогона:

Call#1
Choice: 6
Invalid entry - please reenter.
Choice: 8
Invalid entry - please reenter.
Choice: 1
sortByName

Call#2
Choice: 4
Goodbye!

Call#3
Choice: 0
Invalid entry - please reenter.
Choice: 5
Invalid entry - please reenter.
Choice: 3
sortByAge

Call#4
Choice: 0
Invalid entry - please reenter.
Choice: 8
Invalid entry - please reenter.
Choice: 0
Invalid entry - please reenter.
Choice: 7
Invalid entry - please reenter.
Choice: 2
sortByCost

Call#5
Choice: 8
Invalid entry - please reenter.
Choice: 3
sortByAge

Однако я бы использовал switch...case, чтобы сохранить код в чистоте:

private static void execute() {
    int choice;
    choice = getChoice();
    while (true) {
        System.out.println("Choice: " + choice);
        switch (choice) {
        case 1:
            System.out.println("sortByName");
            return;
        case 2:
            System.out.println("sortByCost");
            return;
        case 3:
            System.out.println("sortByAge");
            return;
        case 4:
            System.out.println("Goodbye!");
            return;
        default:
            System.out.println("Invalid entry - please reenter.");
            choice = getChoice();
        }
    }
}

Надеюсь, это поможет. Не стесняйтесь комментировать в случае каких-либо сомнений / проблем.

...