【问题标题】:Java -- Printing stuff twiceJava——打印两次
【发布时间】:2016-10-07 14:07:36
【问题描述】:

我的程序要求用户输入一个选项(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
    }
}

提前感谢您的帮助!

【问题讨论】:

  • feetInchesToCm 是什么?
  • 投反对票的人,如果您要投反对票,请提供反馈以帮助 OP 了解他做错了什么。没有理由的投票只会使人们远离该网站。我们希望人们回来,但提出有用且有意义的问题。
  • @Dale 没有人有义务在投票后发表评论,但我之所以这样做是因为问题基本上是要求我们进行调试,并且缺少许多重要细节。
  • 我想知道为什么这个问题得到了 -4 票 O.o
  • @Dale 同意。我的回答也解决了这个问题,即使没有提供足够的信息

标签: java loops output


【解决方案1】:

你已经明确地调用了你的方法两次

保存返回值,或者不要再调用它。

例如

  if(choice == 1)
    {
        int cm = feetInchesToCm();
        addConversion(cm);
        System.out.println("");
        System.out.println(cm);
    }

或者,如果您不需要保存值来打印它,只需在返回值上直接调用 addConversion

  if(choice == 1)
    {
        System.out.println("");
        addConversion(feetInchesToCm());
    }

【讨论】:

  • addConversion 被调用,但你从语句分支中删除它?你确定是feetInchesToCm 造成的吗?您可能需要等待 OP 在回答之前澄清它是什么。
猜你喜欢
  • 1970-01-01
  • 2014-02-16
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2014-07-19
  • 2020-09-20
  • 1970-01-01
相关资源
最近更新 更多