I am trying to write a program that takes an integer value (n) from the user, checks that it is greater than 0 and less than 30. If this is the case it calls my catalan numbers method and substitutes n in. If the inputted number is less than 0 or greater than 30 it should throw and IllegalArgumentException.
There doesn't seem to be a problem with the catalan numbers method, but there are when I try and call the catalan numbers method and input 'n' into it. All the problems are confined to the switch statement, where it will not accept the functions 'n.equals("quit"), (n>30), (n < 0), and it won't call my catalan numbers method.
Here is my code so far:
public class Exercise_3 {
public static long catalan(int n) throws IllegalArgumentException {
int res = 0;
// Base case
if (n <=1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan( n - i - 1);
}
return res;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Exercise_3 cn = new Exercise_3();
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
boolean n = scan.nextBoolean(); {
switch(n) {
if (n.equals("quit")) {
break;
}
else
case (n > 30):
throw IllegalArgumentException;
break;
case (n < 0):
throw IllegalArgumentException;
break;
case (0 < n <= 30):
int i = cn(n);
break;
}
System.out.println(i);
}
}
}
If anybody has any solutions to this I would be very grateful.
Your approach in using switch is, sorry for that, completely wrong. This is no JavaScript where you can pass the result of a Promise to a boolean. If you want to use Java, you have to learn a totally different thinking in solving problems. Switch is the worst choice to your problem. Try it with nested If-Statements instead.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
String input = scan.next();
if(!input.equals("quit")) {
int number = Integer.parseInt(input);
if(number < 0 || number > 30) {
throw new IllegalArgumentException("number out of range");
}
else {
int i = catalan(number);
System.out.println(i);
}
}
}