Exception in thread "main" java.util.InputMismatchException. Не могу правильно реализовать if (action.equals("back")){continue;}

272
24 октября 2021, 17:50

Похоже ошибка в неправильном использовании if (action.equals("back")){continue;}. Мне нужно реализовать возвращение в исходное меню при вводе "back"

Код:

import java.util.Scanner;
class CoffeeMachine
 {
    private static int money = 550;
    private static int water = 1200;
    private static int milk = 540;
    private static int beans = 120;
    private static int disCups = 9;
    public static void main(String[] args)
  { int enter = 0;
    int errCode = 0;
    for (; ;) {
    System.out.println("Write action (buy, fill, take, remaining, exit): ");
    System.out.print("> ");
    Scanner scan = new Scanner(System.in);
    String action = scan.nextLine();
    System.out.println();
    if (action.equals("exit")) {System.exit(errCode);}
    else if (action.equals("buy")) {
    System.out.println("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ");
    System.out.print("> ");
    enter = scan.nextInt();
    System.out.println();
    if (action.equals("back")) {continue;}
    else if (enter == 1) { // espresso
        water = water - 250;
        beans = beans - 16;
        money = money + 4;
        disCups = disCups - 1; }
    else if (enter == 2) { // latte
        water = water - 350;
        milk = milk - 75;
        beans = beans - 20;
        money = money + 7;
        disCups = disCups - 1; }
    else if (enter == 3) { // capucino
        water = water - 200;
        milk = milk - 100;
        beans = beans - 12;
        money = money + 6;
        disCups = disCups - 1; }
    else if (action.equals("back")) {return;}
    // machineHas();
    }
    else if (action.equals("fill")){
    System.out.println("Write how many ml of water do you want to add: ");
    System.out.print("> ");
    water = water + scan.nextInt();
    System.out.println();
    System.out.println("Write how many ml of milk do you want to add: ");
    System.out.print("> ");
    milk = milk + scan.nextInt();
    System.out.println();
    System.out.println("Write how many grams of coffee beans do you want to add: ");
    System.out.print("> ");
    beans = beans + scan.nextInt();
    System.out.println();
    System.out.println("Write how many disposable cups of coffee do you want to add: ");
    System.out.print("> ");
    disCups = disCups + scan.nextInt();
    System.out.println();
    }
    else if (action.equals("take")){
    System.out.println("I gave you $" + money);
    money = 0;
    System.out.println();
    }
    else if (action.equals("remaining")){
    System.out.println("The coffee machine has:");
    System.out.println(water + " of water");
    System.out.println(milk + " of milk");
    System.out.println(beans + " of beans");
    System.out.println(disCups + " of disposable cups");
    System.out.println(money + " money"); }
    System.out.println();
  } } }

После запуска:

Write action (buy, fill, take, remaining, exit):

buy

What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:

back

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at CoffeeMachine.main(Coffee.java:235)

Правильный алгоритм работы:

Write action (buy, fill, take, remaining, exit): 
> remaining
The coffee machine has:
400 of water
540 of milk
120 of coffee beans
9 of disposable cups
$550 of money
Write action (buy, fill, take, remaining, exit): 
> buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 
> 2
I have enough resources, making you a coffee!
Write action (buy, fill, take, remaining, exit): 
> remaining
The coffee machine has:
50 of water
465 of milk
100 of coffee beans
8 of disposable cups
$557 of money
Write action (buy, fill, take, remaining, exit): 
> buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 
> 2
Sorry, not enough water!
Write action (buy, fill, take, remaining, exit): 
> fill
Write how many ml of water do you want to add: 
> 1000
Write how many ml of milk do you want to add: 
> 0
Write how many grams of coffee beans do you want to add: 
> 0
Write how many disposable cups of coffee do you want to add: 
> 0
Write action (buy, fill, take, remaining, exit): 
> remaining
The coffee machine has:
1050 of water
465 of milk
100 of coffee beans
8 of disposable cups
$557 of money
Write action (buy, fill, take, remaining, exit): 
> buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 
> 2
I have enough resources, making you a coffee!
Write action (buy, fill, take, remaining, exit): 
> remaining
The coffee machine has:
700 of water
390 of milk
80 of coffee beans
7 of disposable cups
$564 of money
Write action (buy, fill, take, remaining, exit): 
> take
I gave you $564
Write action (buy, fill, take, remaining, exit): 
> remaining
The coffee machine has:
700 of water
390 of milk
80 of coffee beans
7 of disposable cups
0 of money
Write action (buy, fill, take, remaining, exit): 
> exit
Answer 1

всем спасибо, решил так: на входе у меня было число и строка, сначала считывал как строку, потом преобразовал методом в сроку в число

            Scanner scan1 = new Scanner(System.in);
        String enter = scan1.nextLine();
        System.out.println();
        if (enter.equals("back")) {continue;}
        int y = Integer.parseInt(enter);
READ ALSO
Как найти сумму чисел из массива в java?

Как найти сумму чисел из массива в java?

Пытаюсь получить сумму всех чисел

246
Очередь с фиксированным размером и реверс итератором

Очередь с фиксированным размером и реверс итератором

Задача кэшировать некие поступающие объекты отчетов, но в заранее заданном объемеЧто-то вроде new ArrayBlockingQueue<Report>(100), но при определенных...

115
Из-за чего происходит exception?

Из-за чего происходит exception?

Создаю простое приложение для CRUD операцийИспользую postgresql+hibernate+java jdk 11+javafx(jfoenix)

120
Что это за компонент?

Что это за компонент?

Это какой-то новый компонент - выезжающая снизу панель? Несколько раз её виделКак её сделать?

246