Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package u04a1_validateuserinput;
- import java.util.Scanner;
- /**
- *
- * @author leonlewis
- */
- public class U04A1_ValidateUserInput {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String userInput;
- boolean isValid = true;
- System.out.print("Enter a course code to validate (e.g. IT4782): ");
- userInput = input.nextLine();
- /* only to be used with different algorithm
- if(ValidateInput(userInput)){
- System.out.println("Course code " + userInput + " is valid.");
- }
- */
- if (userInput.length() != 6){
- System.out.println("The course code is not the right length.");
- }
- else{
- if(Character.toLowerCase(userInput.charAt(0)) != 'i'){
- System.out.println("First character is not an I or an i");
- isValid = false;
- }
- if(Character.toLowerCase(userInput.charAt(1)) != 't'){
- System.out.println("Second character is not a T or a t");
- isValid = false;
- }
- if(!Character.isDigit(userInput.charAt(2))){
- System.out.println("Third character is not a digit");
- isValid = false;
- }
- if(!Character.isDigit(userInput.charAt(3))){
- System.out.println("Fourth character is not a digit");
- isValid = false;
- }
- if(!Character.isDigit(userInput.charAt(4))){
- System.out.println("Fifth character is not a digit");
- isValid = false;
- }
- if(!Character.isDigit(userInput.charAt(5))){
- System.out.println("Sixth character is not a digit");
- isValid = false;
- }
- if(isValid){
- System.out.println("Course code " + userInput + " is valid.");
- }
- }
- }
- // Different algorithm because I did not like reusing
- // the if statement over and over again.
- private static boolean ValidateInput(String userInput){
- String namedArray[] = {"First", "Second", "Third", "Fourth", "Fifth", "Sixth" };
- String reason[] = {"not an i or an I", "not a t or a T", "not a digit"};
- boolean isValid = true;
- for(int i = 0; i < userInput.length(); i++){
- if(i == 0 || i == 1){
- char tempChar = Character.toLowerCase(userInput.charAt(i));
- String it = "it";
- if(tempChar != it.charAt(i)){
- System.out.println(namedArray[i] + " character is " + reason[i]);
- isValid = false;
- }
- }else {
- if(!Character.isDigit(userInput.charAt(i))){
- System.out.println(namedArray[i] + " character is " + reason[2]);
- isValid = false;
- }
- }
- }
- return isValid;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment