我正在编写一个控制台应用程序。 UI会是这样的。
请输入:
- 学习java
- 学习VB.NET
- 退出
醇>
如果用户输入1将进行java学习,如果输入2将进行VB学习,如果输入3程序将退出。对于所有其他输入,程序将再次显示上述消息。
我以下面的方式实现了这个:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DriverTest {
public static void main(String[] args) {
new DriverTest().takeOver();
}
public void takeOver() {
BufferedReader inputScanner = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter:");
System.out.println("1. to learn JAVA");
System.out.println("2. to learn VB");
System.out.println("3. to quit");
try {
int actionKey = Integer.parseInt(inputScanner.readLine());
switch (actionKey) {
case 1:
System.out.println("Welcome to JAVA learning");
break;
case 2:
System.out.println("Welcome to VB learning");
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Please select a proper action :");
takeOver();
}
} catch (NumberFormatException | IOException e) {
System.out.println("Some error occured please try again. :(");
takeOver();
}
}
}
现在如果用户不断提供无效输入,最终会导致StackOverflow错误。(你可以测试它,复制文件夹中的类吧:javac DriverTest.java,创建一个文本文件input.txt并写入除了1,2和3.例如hgsad,现在运行java DriverTest< input.txt)
如果有更好的解决方案,请提出建议。
答案 0 :(得分:2)
您继续以递归方式调用takeOver()
。如果你这样做了足够多次,你最终会达到调用堆栈溢出的程度。如果你想避免这种情况,请在循环中调用代码而不是使用递归。
答案 1 :(得分:2)
您正在重复调用takeOver()
,因此您不断向堆栈添加已启动的函数,因此StackOverflow
。你应该使用一个循环:
public void takeOver() {
BufferedReader inputScanner = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter:");
boolean inLoop = true;
while(inLoop){
System.out.println("1. to learn JAVA");
System.out.println("2. to learn VB");
System.out.println("3. to quit");
try {
int actionKey = Integer.parseInt(inputScanner.readLine());
switch (actionKey) {
case 1:
System.out.println("Welcome to JAVA learning");
inLoop = false;
break;
case 2:
System.out.println("Welcome to VB learning");
inLoop = false;
break;
case 3:
System.exit(0);
default:
System.out.println("Please select a proper action :");
}
} catch (NumberFormatException | IOException e) {
System.out.println("Some error occured please try again. :(");
}
}
}
答案 2 :(得分:0)
调用takeOver()以递归方式连续添加对堆栈的调用,并收到StackOverflow错误。请改用循环。
public void takeOver() {
BufferedReader inputScanner = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter:");
System.out.println("1. to learn JAVA");
System.out.println("2. to learn VB");
System.out.println("3. to quit");
boolean continue = true;
while(continue)
{
int actionKey = Integer.parseInt(inputScanner.readLine());
switch (actionKey) {
case 1:
System.out.println("Welcome to JAVA learning");
continue = false;
case 2:
System.out.println("Welcome to VB learning");
continue = false;
case 3:
System.exit(0);
continue = false;
default:
System.out.println("Please select a proper action :");
}
}
}