Classify a Token (instanceof Pattern)
Problem
Read one token. If it is a whole number, print integer followed by the number doubled. Otherwise print word followed by the token in capital letters.
Constraints
- The token has no spaces
Examples
Input
21
Output
integer 42
Input
hello
Output
word HELLO
Solutions
Before Java 16 a type test needs a separate cast line. The cast can be wrong if the test and the cast are not kept together.
/*
* Problem : Classify a token.
* Input : One token.
* Output : A description.
* Approach: Type test.
* 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 s) {
// Step 1: Make an Object that is an Integer if the text is a number, otherwise a String.
Object token;
try {
token = Integer.valueOf(s.trim());
} catch (NumberFormatException error) {
token = s.trim();
}
// Step 2: Before Java 16 we test the type, then cast the object in a second step.
if (token instanceof Integer) {
Integer number = (Integer) token;
return "integer " + (number * 2);
}
String word = (String) token;
return "word " + word.toUpperCase();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Why can a separate cast be risky?