Программа повторяет случай переключения из-за невозможности снова получить пользовательский ввод во время цикла

Я почти закончил Java-проект для вводного класса, где пользователь должен выполнять преобразования по стоимости бензина. Программа работает нормально, когда я запускаю ее через командную строку, до момента, когда вы выбираете преобразование (из вариантов 1, 2, 3, 4 или 5).

Что происходит, так это то, что программа вычисляет это нормально и отображает часть «Введите NO, если вы хотите выйти» просто отлично, но затем она повторяет программу до того, как пользователь имеет возможность даже напечатать что-либо. Я не уверен, что делать здесь. Я попытался ввести keyboard.nextLine();, чтобы перейти к строке, которую пользователь мог отправить, но произошла та же ошибка. Если я изменю строку внизу, чтобы запустить цикл, в то время как yesOrNo = yes, программа резко остановится. Я предполагаю, что это та же проблема, хотя я не уверен, что делать, и я не смог найти эту проблему в других сообщениях на форуме. Спасибо всем, кто решит помочь.

Вот мой код без заголовков основного метода/класса:

    // Ask the user for their name
    System.out.println("What is your name?");

    // Use Scanner to get the user's name (a string variable)
    String name = keyboard.nextLine();

    // Welcome the user by name & give a readable description of the program using escape sequences
    System.out.println(name + ", welcome. I am Rachel and this program will help you perform gasoline analysis.\n");
    System.out.println("Using this program, you can extract information about any amount of gallons of gasoline, such as:");
    System.out.println("its equivalent in liters, its price, and how much oil is required to produce it, for example.\n");
    System.out.println("Press any letter to continue.");

    String yesOrNo = keyboard.next();
    boolean performConversion = true;


    // Perform the conversions the user wants at least once, until they want to stop. 
    do 
{
        // Get the value of gallons (floating-point value) of gasoline from the user.
            System.out.println("Please enter a number that will represent your gallons of gasoline.");
            double userGallons = keyboard.nextDouble();

        // Declare variables and convert the gallons to the other units of measurement. 
            double liters = (userGallons * 3.7854);

            double barrelsNeeded = (userGallons / 19.5);

            double poundsCO2 = (userGallons * 20.0);

            double ethanolEnergy = (userGallons * 75700);

            double price = (userGallons * 4.0);

        // Show the user a menu of their choices for conversion.
            System.out.println("Select the conversion you would like to perform here:");
            System.out.println("Press 1 for liters");
            System.out.println("2 for pounds of CO2 produced");
            System.out.println("3 for equivalent energy amount of ethanol gallons");
            System.out.println("4 for price in USD");
            System.out.println("or 5 for barrels of oil required to produce that amount of gasoline.");
            int userChoice = keyboard.nextInt();

        // Display the original gallons and the available conversions to the user. 

        switch(userChoice)
        {
            case 1:
                System.out.println("Original gallons of gasoline: " + userGallons + "gallons");
                System.out.println("Amount in liters: " + liters);
                System.out.println("Type NO if you want to exit, or any other key to continue.");
                break;
            case 2:
                performConversion = true;
                System.out.println("Original gallons of gasoline: " + userGallons + "gallons");
                System.out.println("Pounds of CO2 produced : " + poundsCO2);
                System.out.println("Type NO if you want to exit, or any other key to continue.");
                break;
            case 3:
                performConversion = true;
                System.out.println("Original gallons of gasoline: " + userGallons + "gallons");
                System.out.println("Equivalent energy amount in ethanol gallons: " + ethanolEnergy + " BTU");
                System.out.println("Type NO if you want to exit, or any other key to continue.");
                break;
            case 4:
                performConversion = true;
                System.out.println("Original gallons of gasoline: " + userGallons + "gallons");
                System.out.println("Price in USD: $" + price);
                System.out.println("Type NO if you want to exit, or any other key to continue.");
                break;
            case 5:
                performConversion = true;
                System.out.println("Original gallons of gasoline: " + userGallons + "gallons");
                System.out.println("Number of barrels of oil needed to produce that amount of gallons: " + barrelsNeeded);
                System.out.println("Type NO if you want to exit, or any other key to continue.");
                break;
            default:
                System.out.println("Invalid character. Please enter 1, 2, 3, 4, or 5.");
        }
    } while (!"no".equalsIgnoreCase(yesOrNo));
    System.out.println("Goodbye! The program will now end.");
}

}


person Rachel    schedule 01.02.2019    source источник
comment
Вы никогда не меняете значение переменной yesOrNo внутри цикла, так что условие while просто продолжается. Может быть, добавить дополнительный пункт, чтобы, если они вводят 0 галлонов, вы установили его нет?   -  person racraman    schedule 01.02.2019


Ответы (2)


Без какой-либо реструктуризации вы можете изменить свое состояние while следующим образом:

} while (!"no".equalsIgnoreCase(keyboard.next()) );
person glumplum    schedule 01.02.2019
comment
Благодарю вас! Это сработало, я убивал себя, пытаясь сделать это, но на самом деле это было намного проще, чем я думал... - person Rachel; 01.02.2019

Поскольку вы хотите, чтобы преобразование произошло хотя бы один раз, я предлагаю вам переместить эти два оператора (упомянутые ниже) внутри цикла do { //... } while(); в самый конец (т.е. после оператора switch...case):

System.out.println("Press any letter to continue.");

String yesOrNo = keyboard.next();

Причина

То, чего вы пытаетесь достичь, заключается в том, чтобы пользователь выполнил преобразование, а затем после того, как ему предоставляется выбор, продолжать или нет.

Текущая программа не запрашивает у пользователя этот выбор. Вместо этого он просто зацикливается, используя значение переменной yesOrNo, которое было установлено до входа в цикл.

Сохранение вышеупомянутых операторов в самом конце цикла должно дать вам желаемые результаты.

Кроме того, я вижу, что вы создали переменную performConversion, однако она никогда нигде не используется (по крайней мере, не в предоставленном фрагменте кода). Поэтому, если эта переменная не используется где-то еще в методе main(), я предлагаю вам удалить ее.

person Dhruv Joshi    schedule 01.02.2019