Guarded Pattern Switch: Classify a Value
Problem
Read a kind (int or text) and a value. For an int: print big integer if it is 1000 or more, integer if it is 0 to 999, negative integer if below 0. For a text: print long text if it has more than 8 letters, otherwise text.
Constraints
- kind is int or text
- int values fit in long
Examples
Input
int 1500
Output
big integer
Input
text hello
Output
text
Solutions
Nested if statements check the type first and the value second. They work everywhere, but each branch has its own indentation and the cases are not listed side by side.
/*
* Problem : Name the kind.
* Input : Kind and value.
* Output : The class name.
* Approach: Nested if
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String a, String b) {
// Step 1: Without guards: test the kind first, then test the value with a nested if.
if (a.equals("int")) {
long n = Long.parseLong(b);
if (n >= 1000) {
return "big integer";
}
return n >= 0 ? "integer" : "negative integer";
}
return b.length() > 8 ? "long text" : "text";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (1)
- Which check must come first?