как я могу зациклить код, если введена неверная опция - PullRequest
0 голосов
/ 06 марта 2019

Программа отслеживает расходы и должна быть безошибочной. Для достижения этой цели мне нужно перезапустить все, начиная со строки 11 и далее.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int Size;
    int order;
    System.out.println("Put in the amount of expenses you have");
    Size = sc.nextInt();
    System.out.println("put in all your expenses");
    int userInput[] = new int[Size];
    for (int i = 0; i < userInput.length; i++)
        userInput[i] = sc.nextInt();
    System.out
            .println("do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
    order = sc.nextInt();
    System.out.print("expenses not sorted : ");
    printExpenses(userInput);
    if (order == 1) {
        expensesAscending(userInput);
    } else if (order == 2) {
        expensedescending(userInput);
    }else if (order>2){
        //How do i make it so that if they press three or above the program restarts
    }
}

Ответы [ 2 ]

0 голосов
/ 06 марта 2019

Без предоставления вам кода то, что вам нужно, называется while loop . В то время как циклы будут продолжать «делать вещи» (в этом случае попытаться заставить пользователя ввести правильный ввод), пока не будет выполнено условие (в этом случае значение порядка равно 1 или 2).

Например:

int order = null; 
while (order != 1 && order != 2){
    System.out.println("do you want it ascending or descending order."
        + "If you want it in ascending press 1 or if you want descending press 2");
    order = sc.nextInt(); 
}

Однако я также думаю, что вы, возможно, захотите пересмотреть свой дизайн интерфейса. Обработка ошибок и неправильных вводов важна, но она облегчает пользователям работу с первой попытки. Например, пользователям было бы проще запомнить, как получить желаемый результат, введя «a» для возрастания и «d» для убывания.

0 голосов
/ 06 марта 2019

Вы можете использовать вечный цикл, пока пользователь не введет правильную запись:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int Size;
    int order;
    int userInput[];
    do { // loop starts here
        System.out.println("Put in the amount of expenses you have");
        Size = sc.nextInt();
        System.out.println("put in all your expenses");
        userInput = new int[Size];
        for (int i = 0; i < userInput.length; i++)
            userInput[i] = sc.nextInt();
        System.out.println(
                "do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
        order = sc.nextInt();
    } while (order < 1 || order > 2); // if the input is not 1 or 2, it goes back
    System.out.print("expenses not sorted : ");
    printExpenses(userInput);
    if (order == 1) {
        expensesAscending(userInput);
    } else {
        expensedescending(userInput);
    }
}

Однако я не рекомендую перезапускать всю программу, если пользователь допустил ошибку.Желательно, чтобы спросить его ввод еще раз или он хочет перезапустить всю программу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...