【发布时间】: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