I am writing a console application. UI would be like this.
Please input :
- to learn java
- to learn VB.NET
- to quit
if user enters 1 it will go for java learning, if enters 2 it will go for VB learning, if enters 3 program will quit. For all other inputs the program will show the above message again.
I implemented this in below way :
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();
}
}
}
Now if user continuously provide invalid input, it will result eventually into StackOverflow error.(You can test it, copy the class in folder.complie it : javac DriverTest.java, create one text file input.txt and write anything except 1,2 and 3. e.g. hgsad, now run java DriverTest < input.txt)
Please suggest, if there is any better solution of the problem.