Я почти закончил 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.");
}
}