/* * Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007) * Date: 2022-04-25 * Description: This is the CLI class. */ import java.util.InputMismatchException; import java.util.Scanner; public class CLI { private static Scanner input = new Scanner(System.in); /** * Read one line from CLI. * * @param message Hint printed to screen * @return one line input */ private static String readLine(String message) { System.out.print(message); return input.nextLine(); } /** * Read one positive integer. * * @param message HINT printed to screen * @return one positive integer */ private static int readPosInt(String message) { while (true) { System.out.print(message); try { int result = input.nextInt(); input.nextLine(); if (result >= 0) { return result; } else { System.out.println("Positive integers only!"); } } catch (InputMismatchException e) { System.out.println("You must type an integer!"); input.nextLine(); } } } public static void main(String[] args) { String str1 = readLine("Type some text: "); System.out.println("Text read is: " + str1); int i = readPosInt("Type an integer: "); System.out.println("Integer read is: " + i); String str2 = readLine("Type some text: "); System.out.println("Text read is: " + str2); } }