【发布时间】:2014-06-21 03:54:48
【问题描述】:
所以我正在研究一堆基本的编程想法来帮助我掌握 Java 的窍门,我创建了一个程序,可以将 PI 打印到小数点后 10 位(如果我愿意,我可以添加更多)。
但是,我决定多做一步,创建一个选项,让程序反复运行,直到用户告诉它停止。我创建了一个方法来返回 true(再次运行)或 false(退出程序)。最初我在该方法中创建了一个扫描仪来获取用户输入,并且程序以这种方式运行良好,但它告诉我我有资源泄漏,因为我没有在该方法中关闭扫描仪。
我刚刚将输入扫描器作为参数从 main 传递给方法,但是当我运行程序时,它不接受用户输入并会打印出“抱歉,出现错误”(else{} 选项在我的方法中的 if-else 语句中)。现在,我可以回去创建一个单独的扫描仪,但我的强迫症不希望 Eclipse 告诉我有资源泄漏(我认为 input.close() 会关闭两个扫描仪,但我不确定)。
这是我的代码,我向所有被我不知道的不良做法迷住和冒犯的 Java 爱好者道歉,我正在学习。
import java.util.Scanner;
import java.text.DecimalFormat;
public class PiDecimalFormat {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat format = new DecimalFormat("#");
int decPlace = 0;
boolean runProgram = true;
System.out.println("This program will print out PI to the decimal place of your choosing.");
while (runProgram == true) {
System.out.print("\nEnter the number of decimal places (up to 10) that \nyou would like to print PI to: ");
decPlace = input.nextInt();
switch (decPlace) {
case 0:
format = new DecimalFormat("#");
break;
case 1:
format = new DecimalFormat("#.#");
break;
case 2:
format = new DecimalFormat("#.##");
break;
case 3:
format = new DecimalFormat("#.###");
break;
case 4:
format = new DecimalFormat("#.####");
break;
case 5:
format = new DecimalFormat("#.#####");
break;
case 6:
format = new DecimalFormat("#.######");
break;
case 7:
format = new DecimalFormat("#.#######");
break;
case 8:
format = new DecimalFormat("#.########");
break;
case 9:
format = new DecimalFormat("#.#########");
break;
case 10:
format = new DecimalFormat("#.##########");
break;
}
System.out.println("\nThe value of PI to " + decPlace + " decimal places is " + format.format(Math.PI) + ".");
runProgram = AskRunAgain(input);
}
input.close();
}
static boolean AskRunAgain(Scanner askUser) {
String userChoice;
System.out.print("\nWould you like to run the program again? [y/n]: ");
userChoice = askUser.nextLine();
if ((userChoice.equals("y")) || (userChoice.equals("Y")) || (userChoice.equals("yes")) ||
(userChoice.equals("Yes")) || (userChoice.equals("YES"))) {
return true;
}
else if ((userChoice.equals("n")) || (userChoice.equals("N")) || (userChoice.equals("no")) ||
(userChoice.equals("No")) || (userChoice.equals("NO"))) {
System.out.println("\nExitting the program. have a good day!");
return false;
}
else {
System.out.println("Sorry, there was an error.");
return false;
}
}
}
如果有人能告诉我为什么这样做,我将不胜感激。我是 Java 新手(C/C++/C# 和 Python 不错)。我没有看到关于这个特定问题的其他问题,如果我只是在该方法中创建另一个扫描仪,这没什么大不了的。
【问题讨论】:
-
如果您打印出
println中AskRunAgain()方法中的userChoice 是什么,它会打印出什么?
标签: java methods java.util.scanner