My program asks the user to enter a choice (1, 2, 3, or 0). Choice 1 asks the user to enter feet and inches. Choice 2 asks the user to enter centimeters. Each time I do this, the program prints double of what I need (please see below):
Enter choice: 1
Enter feet: 12
Enter inches: 2
Enter feet: 12 //This second part should not happen
Enter inches: 2
I have tried commenting out the addConversion(...)
line, but this does not allow me to print choice 3 properly. When I comment out System.out.println(feetInchesToCm())
my conversion for that case is not printed.
The main function of my code is as follows:
public static void main(String[] args) throws NumberFormatException, IOException
{
int choice;
do
{
displayMenu();
choice = getInteger("\nEnter choice: ", 0, Integer.MAX_VALUE);
if(choice == 1)
{
addConversion(feetInchesToCm());
System.out.println("");
System.out.println(feetInchesToCm());
}
else if(choice == 2)
{
addConversion(cmTofeetInches());
System.out.println("");
System.out.println(cmTofeetInches());
}
else if(choice == 3)
{
if(_prevConversions == null)
{
break;
}
else if(_prevConversions != null)
{
for(int i = 1; i <= _numConversions; i++)
{
System.out.print("Conversion # " + i + ": ");
System.out.println(_prevConversions[i]);
}
}
}
}while(choice != 0);
if(choice == 0)
{
System.out.println("\nGoodbye!");
System.exit(0); //Ends program
}
}
Thank you in advance for your assistance!
You've explicitly called your method twice
Save the return value, or don't call it again.
For example
if(choice == 1)
{
int cm = feetInchesToCm();
addConversion(cm);
System.out.println("");
System.out.println(cm);
}
Or, if you don't need to save the value in order to print it, just call addConversion directly on the returned value
if(choice == 1)
{
System.out.println("");
addConversion(feetInchesToCm());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.