Alphanumeric input of 25 length

... by Bittle in Programming Help November 08, 2018

Problem

Write a program that will accept 25 alphanumeric characters. Accept the input 5 characters at a time and output them in all uppercase separated by a hyphen.


Example output: ASDFA-ASDFW-234AS-ALSDF-ASDFQ


Solution

Check that the input is alphanumeric and of length 5 using the regular expression

[a-zA-Z0-9]{5}

If incorrect input we keep asking until the input is correct. Java solution:

// get input from keyboard
    Scanner scanner = new Scanner(System.in);
    StringBuilder all = new StringBuilder();
    // x = 0...4 since question wants 5 strings
    for (int x = 0; x < 5; x++) {
        System.out.print("> ");
        String five = scanner.next();
        while (!five.matches("[a-zA-Z0-9]{5}")) {
            // has to be alphanumeric with five length (keep asking if incorrect)
            System.out.print("Input must be alphanumeric and of five length." +
                    "\n> ");
            five = scanner.next();
        }

        all.append(five);
        if (x != 4) {
            // don't append - after last string
            all.append('-');
        }
    }

    // question asks for all caps
    System.out.println("OUTPUT: " + all.toString().toUpperCase());
}

Comments (0)

Search Here