【问题标题】:While loop & BufferedReaderWhile 循环 & BufferedReader
【发布时间】:2015-09-10 00:17:09
【问题描述】:

我正在处理课堂作业,但在设置用户通过输入 Q 或 q 退出程序时遇到问题。

我的教授不允许我们使用 Scanner,因为他出于某种原因不喜欢它,而且我以前从未使用过 BufferedReader,我一直有点困惑。此外,他不希望我们提示用户,否则我只会在最后设置一些内容,即按 Enter 继续或 Q/q 退出。但我不确定如何处理它,有什么建议吗?截至目前,如果我选择使用 q 退出,我会收到一个错误,因为我已将所有输入解析为双精度数。

感谢您的帮助,下面是我的代码。

public class CST200_Lab2 {  

  public static void main(String[] args) throws IOException {
    String inputString = " ";

    double hullSpeed;
    double displacementEqu;
    double sailAreaEqu;
    double capSize;
    double comfortIndex;

    InputStreamReader ISR = new InputStreamReader(System.in);
    BufferedReader BR = new BufferedReader(ISR);

    NumberFormat NF = NumberFormat.getNumberInstance();
    NF.setMaximumFractionDigits(2);
    NF.setMinimumFractionDigits(2);

    while(!(inputString.equalsIgnoreCase("q"))) {

        //Input for the Length of the vessel
        inputString = BR.readLine();
        double lengthVesselDbl = Double.parseDouble(inputString);

        //Input for the water line length for the Vessel
        inputString = BR.readLine();
        double waterLineLengthDbl = Double.parseDouble(inputString);

        //Input for the Beam / width of the vessel
        inputString = BR.readLine();
        double widthVesselDbl = Double.parseDouble(inputString);

        //Input for the displacement
        inputString = BR.readLine();
        double displacementDbl = Double.parseDouble(inputString);

        //Input for the Sail Area
        inputString = BR.readLine();
        double sailAreaDbl = Double.parseDouble(inputString);

        /**EQUATIONS*/
        //Calculate the Hull Speed
        hullSpeed = 1.34 * (Math.pow(waterLineLengthDbl, .5));

        //Calculate Displacement to Waterline Length
        displacementEqu = (displacementDbl / 2240.00) / Math.pow((.01 * waterLineLengthDbl), 3);

        //Calculate Sail Area to Displacement
        sailAreaEqu = sailAreaDbl / Math.pow((displacementDbl / 64.00), .67);

        //Calculate the Capsize index.
        capSize = widthVesselDbl / Math.pow((displacementDbl / 64.00), .33);

        //Calculate the Comfort index
        comfortIndex = (displacementDbl) / (.65*(.7 * waterLineLengthDbl 
                + .3 * lengthVesselDbl) * Math.pow((widthVesselDbl), 1.33));

        //Print out the User input 
        System.out.println("LOA: " + NF.format(lengthVesselDbl));
        System.out.println("LWL: " + NF.format(waterLineLengthDbl));
        System.out.println("BEAM: " + NF.format(displacementDbl));

    };
}
}

****更新****

根据你们中的一些人的建议,我仍然遇到问题。该建议的问题在于它现在要求 6 个用户输入,而不是程序所需的 5 个。此外,如果您在程序中途退出,您会收到与之前相同的错误...

Exception in thread "main" java.lang.NumberFormatException: For input string: "Q"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at CST200_Lab2.main(CST200_Lab2.java:38)

**********新更新**************

这就是我现在正在做的事情,它似乎正在工作。这是一条好走的路吗。有没有更好的方法来编写这个,以便用户可以随时输入 Q 并结束程序?我似乎找不到方法,因为输入被解析为双精度。

while(!(exit.equalsIgnoreCase("q")) && !(exit.equals(null))) {

在While循环结束时

exit = BR.readLine();

【问题讨论】:

    标签: java while-loop bufferedreader exit


    【解决方案1】:

    不清楚您要做什么,因为您似乎在 while 循环内多次从控制台读取。但是,当用户通过控制台输入 qQ 时,这将允许循环终止:

    String inputString = "";
    
    //assign the trimmed user input line to inputString and check if it equals q ignoring case
    while ((inputString = BR.readLine()) != null && (!inputString.equalsIgnoreCase("q"))) {
           //do stuff with inputString in while loop
    }
    

    如果您可以添加更多详细信息,我可以在答案中添加更多内容。

    更新

    在您在 cmets 中澄清您想要什么之后,我只更改了循环以执行您想要的操作,并将变量(您在 while 循环中的)放在外面:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.text.NumberFormat;
    
    public class CST200_Lab2 {
    
        public static void main(String[] args) throws Exception {
            String inputString = "";
    
            double hullSpeed;
            double displacementEqu;
            double sailAreaEqu;
            double capSize;
            double comfortIndex;
    
            // declare variables outside the loop to be preserved
            // initialize at -1 because length and area can't be negative
            // and because my compiler requires initialization
            double lengthVesselDbl = -1;
            double waterLineLengthDbl = -1;
            double widthVesselDbl = -1;
            double displacementDbl = -1;
            double sailAreaDbl = -1;
    
            InputStreamReader ISR = new InputStreamReader(System.in);
            BufferedReader BR = new BufferedReader(ISR);
    
            NumberFormat NF = NumberFormat.getNumberInstance();
            NF.setMaximumFractionDigits(2);
            NF.setMinimumFractionDigits(2);
    
            System.out.println("Starting program!");
    
            int i = 1;
    
            // loop and read input, and assign to proper variable
            while ((inputString = BR.readLine()) != null && (!inputString.equalsIgnoreCase("q"))) {
                try {
                    switch (i) {
                    case 1:
                        lengthVesselDbl = Double.parseDouble(inputString);
                        break;
    
                    case 2:
                        waterLineLengthDbl = Double.parseDouble(inputString);
                        break;
    
                    case 3:
                        widthVesselDbl = Double.parseDouble(inputString);
                        break;
    
                    case 4:
                        displacementDbl = Double.parseDouble(inputString);
                        break;
    
                    case 5:
                        sailAreaDbl = Double.parseDouble(inputString);
                        break;
    
                    default:
                        System.out.println("Input is not being used. Press Q to exit!");
                        break;
                    }
                    i++;
                } catch (NumberFormatException e) {
                    System.out.println("Please enter a number!");
                }
            }
    
            // check if variables were assigned properly
            if (lengthVesselDbl >= 0 && waterLineLengthDbl >= 0 && widthVesselDbl >= 0 && displacementDbl >= 0
                    && sailAreaDbl >= 0) {
    
                // Calculate the Hull Speed
                hullSpeed = 1.34 * (Math.pow(waterLineLengthDbl, .5));
    
                // Calculate Displacement to Waterline Length
                displacementEqu = (displacementDbl / 2240.00) / Math.pow((.01 * waterLineLengthDbl), 3);
    
                // Calculate Sail Area to Displacement
                sailAreaEqu = sailAreaDbl / Math.pow((displacementDbl / 64.00), .67);
    
                // Calculate the Capsize index.
                capSize = widthVesselDbl / Math.pow((displacementDbl / 64.00), .33);
    
                // Calculate the Comfort index
                comfortIndex = (displacementDbl)
                        / (.65 * (.7 * waterLineLengthDbl + .3 * lengthVesselDbl) * Math.pow((widthVesselDbl), 1.33));
    
                // Print out the User input
                System.out.println("LOA: " + NF.format(lengthVesselDbl));
                System.out.println("LWL: " + NF.format(waterLineLengthDbl));
                System.out.println("BEAM: " + NF.format(displacementDbl));
            } else {
                throw new Exception("Dimensions weren't initialized!");
            }
        }
    }
    

    既然你说它假设用户知道何时输入什么维度或值,我做了switch 语句,以便基于循环的迭代,用户输入的值被分配给适当的变量,因为每次迭代读入用户输入。在第 5 次迭代之后,用户提供的输入没有任何反应,一旦用户输入 Q,循环就会终止。

    【讨论】:

    • 它也会得到一个NullPointerException
    • 本质上它是一个用于船只的“计算器”。我还没有完成,但它从用户那里读取了 5 个数字,然后使用用户输入为一艘船计算了 5 个单独的东西。你所拥有的问题是它似乎提示输入第 6 次
    • @user3862586 所以假设用户知道数字应该按什么顺序排列?所以我知道先输入容器长度,然后输入水线长度,等等?然后用户输入所有 5 个数字后,他们键入“q”以终止循环并获得结果?而这一切都没有任何提示?我的理解正确吗?
    • 是的,这是正确的。我假设这对退出也是正确的。我明天要在课堂上问教授。我不确定他是否希望用户能够随时输入 Q 退出。
    【解决方案2】:

    您需要检查流的结尾,并且您正在检查刚刚输入的行之前的行。试试这个:

    while ((inputString = BR.readLine()) != null && !inputString.equalsIgnoreCase("q"))
    

    【讨论】:

    • 好的。这是否允许用户随时退出?您能解释一下为什么它会按原样给出错误吗?我认为是因为我将其解析为双精度数?
    • 我尝试了你所拥有的,当你完成时它会退出程序,但是它现在需要 6 个输入而不是需要的 5 个。
    • @user3862586 因为你没有删除内部的readLine() 调用。
    【解决方案3】:

    这对我有用:

    while (!(line = scan.readLine()).isEmpty())
    

    对于这个问题,我想这就像你的问题: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 1970-01-01
      • 2016-09-10
      • 2013-12-21
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 2012-10-13
      • 2011-05-31
      相关资源
      最近更新 更多