Запрограммировать повторяющиеся переключения из-за невозможности повторного ввода пользовательского ввода во время цикла - PullRequest
0 голосов
/ 01 февраля 2019

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

Что происходит, так это то, что программа прекрасно ее вычисляет и отображает часть «Введите НЕТ, если вы хотите выйти», но затем она повторяет программу, прежде чем у пользователя появится возможность что-либо напечатать.Я не уверен, что делать здесь.Я попытался набрать 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.");
}

}

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

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

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

String yesOrNo = keyboard.next();

Причина

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

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

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

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

0 голосов
/ 01 февраля 2019

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

} while (!"no".equalsIgnoreCase(keyboard.next()) );
...