vendredi 17 juin 2016

Ignoring digits, blank spaces and read String input, using Character.isLetter & Character.isDigit

I have been stuck for quite some time. I would need to ignore digits entered, blank spaces and special characters like $^%##&! and just read the other letters a-z, using Character.isDigit & Character.isLetter.. I have tried using the both methods, it didn't work out for me.. Please advice.. The error image : Img1 The normal output (without spaces and digits) : Img2

The expected output should be 438-5626 even when I entered 123$@GetLoan.. They should ignore the first few characters '123$@' and read only GetLoan..

Full Question: Write a program that prompts the user to enter a telephone number expressed in letters and outputs the corresponding telephone number in digits. If the user enters more than seven letters, then process only the first seven letters. Also output the – (hyphen) after the third digit. Allow the user to use both uppercase and lowercase letters as well as spaces between words.

public class Question3 {

public static void main(String[] args) {

    String letters;
    char phoneDigit;

    Scanner kb = new Scanner(System.in);

    System.out.println("Enter letters : ");
    letters = kb.next();

    for (int i = 0; i < 7; i++) {

        phoneDigit = letters.charAt(i);

        if (Character.isLetter(phoneDigit) == true) {

            if (i == 3) {
                System.out.println("-");
            } //If 

            if (phoneDigit >= 'A' && phoneDigit <= 'C'
                    || phoneDigit >= 'a' && phoneDigit <= 'c') {

                System.out.println("2");

            } else if (phoneDigit >= 'D' && phoneDigit <= 'F'
                    || phoneDigit >= 'd' && phoneDigit <= 'f') {

                System.out.println("3");

            } else if (phoneDigit >= 'G' && phoneDigit <= 'I'
                    || phoneDigit >= 'g' && phoneDigit <= 'i') {

                System.out.println("4");

            } else if (phoneDigit >= 'J' && phoneDigit <= 'L'
                    || phoneDigit >= 'j' && phoneDigit <= 'l') {

                System.out.println("5");

            } else if (phoneDigit >= 'M' && phoneDigit <= 'O'
                    || phoneDigit >= 'm' && phoneDigit <= 'o') {

                System.out.println("6");

            } else if (phoneDigit >= 'P' && phoneDigit <= 'S'
                    || phoneDigit >= 'p' && phoneDigit <= 's') {

                System.out.println("7");

            } else if (phoneDigit >= 'T' && phoneDigit <= 'V'
                    || phoneDigit >= 't' && phoneDigit <= 'v') {

                System.out.println("8");

            } else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
                    || phoneDigit >= 'W' && phoneDigit <= 'z') {

                System.out.println("9");
            } // If
        } // If
    } // For loop

} //PSVM

Aucun commentaire:

Enregistrer un commentaire