[英]Java -- Printing stuff twice
我的程序要求用戶輸入一個選項(1、2、3 或 0)。 選項 1 要求用戶輸入英尺和英寸。 選項 2 要求用戶輸入厘米。 每次我這樣做時,程序都會打印出我需要的兩倍(請參見下文):
Enter choice: 1
Enter feet: 12
Enter inches: 2
Enter feet: 12 //This second part should not happen
Enter inches: 2
我嘗試注釋掉addConversion(...)
行,但這不允許我正確打印選項 3。 當我注釋掉System.out.println(feetInchesToCm())
我的轉換沒有打印出來。
我的代碼的主要功能如下:
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
}
}
預先感謝您的幫助!
你已經明確調用了你的方法兩次
保存返回值,或者不再調用它。
例如
if(choice == 1)
{
int cm = feetInchesToCm();
addConversion(cm);
System.out.println("");
System.out.println(cm);
}
或者,如果您不需要保存值來打印它,只需直接在返回值上調用 addConversion
if(choice == 1)
{
System.out.println("");
addConversion(feetInchesToCm());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.