Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CahracterCheck {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in); // Create a Scanner object
- String input = ""; // Initialize input string
- // do-while loop
- do {
- System.out.print("Enter a character: "); // ask for a character
- input = scanner.next(); // Read user input
- String charType = getCharacterType(input); // get the character type
- System.out.println("Character is: " + charType); // Output user input
- System.out.println("---------------------"); // new line
- } while (!isEnd(input)); // loop runs until "done" is encountered
- // encountered
- scanner.close();
- System.out.println("===== THANK YOU =====");
- }
- // function to check the character type
- private static String getCharacterType(String input) {
- if (input.length() > 1) {
- if (isEnd(input)) {
- return "TERMINATION"; // if the input is "done" return the type "TERMINATION"
- } else {
- return "INVALID"; // return invalid as the input contains more than one charcacter and is not
- // "done"
- }
- } else {
- char c = input.charAt(0); // getting the character at 0 position of input
- // ASCII Values
- // 0-9 >> 48-57
- // A-Z >> 65-90
- // a-z >> 97-122
- if (c >= 48 && c <= 57) {
- return "NUMBER"; // from 48 till 57 the character is number
- } else if (c >= 65 && c <= 90) {
- return "CAPITAL LETTER";// from 65 till 90 the character is capital letter
- } else if (c >= 97 && c <= 122) {
- return "SMALL LETTER";// from 97 till 122 the character is small letter
- } else {
- return "SPECIAL SYMBOL";// else the character is special symbol
- }
- }
- }
- // check if the program is to end
- private static boolean isEnd(String input) {
- if (input.length() == 4) {
- char[] c = input.toCharArray(); // input string converted to char array for simplicity
- if ((c[0] == 'D' || c[0] == 'd') && (c[1] == 'O' || c[1] == 'o') && (c[2] == 'N' || c[2] == 'n')
- && (c[3] == 'E' || c[3] == 'e')) {
- return true; // if DONE is encountered in any combination eg; DoNe, done, DONE, donE, etc the
- } // program ends
- else {
- return false; // else the program doesn't end as the input is not "DONE"
- }
- } else {
- return false; // if input length is not 4 the program continues as "done" contains exactly 4
- } // letters
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement