guccimanilla
guccimanilla

Reputation: 33

How to convert characters from a string into numbers (phone number converted)?

I'm a bit stuck on how I should replace each element in char array to a number.

Here's the code I have so far:

 public static void main(String []args){

    String[] dialTwo = {"a", "b", "c"};
    String[] dialThree = {"d", "e", "f"};
    String[] dialFour = {"g", "h", "i"};
    String[] dialFive = {"j", "k", "l"};
    String[] dialSix = {"m", "n", "o"};
    String[] dialSeven = {"p", "q", "r", "s"};
    String[] dialEight = {"t", "u", "v"};
    String[] dialNine = {"w", "x", "y", "z"};

    Scanner in = new Scanner(System.in);

    System.out.print("Enter a phone number: ");
    String phoneInput = in.next();
    char[] inputToArray = phoneInput.toCharArray();


    while (!phoneInput.matches("^[a-pA-P0-9]*$")) {
        System.out.println("Not a valid number. Try agian.");
        phoneInput = in.next();
    }

I was able to successfully verify the string in case someone wanted to enter ;;';';.

Thank you for your help guys.

My teacher also wants me to use method classes, but I'm slightly confused on it so I'm doing it a bit differently.

So the output I want, if someone were to input "CFG" it would print 123.

Upvotes: 3

Views: 1056

Answers (5)

Dhaval Simaria
Dhaval Simaria

Reputation: 1964

We can use Regular Expression(regex) here to find alphabets in the input and replace each with corresponding integer till entire value contains integers.

Add the following code:

/*Search and replace all alphabets till only numbers are left in the string*/
while(phoneInput.matches("^[a-zA-Z0-9]*$") && !phoneInput.matches("^[0-9]*$")){
        /*
        * Scenario 1:
        * The regex used will search for one occurrence of alphabets a, b & c(both upper and lower case) 
        * and replace with "1". 
        * Same goes down for other values as well.
        */
        phoneInput = phoneInput.replaceFirst("[a-cA-C]", "2"); 
        phoneInput = phoneInput.replaceFirst("[d-fD-F]", "3");
        phoneInput = phoneInput.replaceFirst("[g-iG-I]", "4");
        phoneInput = phoneInput.replaceFirst("[j-lJ-L]", "5");
        phoneInput = phoneInput.replaceFirst("[m-oM-O]", "6");
        phoneInput = phoneInput.replaceFirst("[p-sP-S]", "7");
        phoneInput = phoneInput.replaceFirst("[t-vT-V]", "8");
        phoneInput = phoneInput.replaceFirst("[w-zW-Z]", "9");
    }

System.out.println("The formatted phone number is: " + phoneInput);

This should serve the purpose.

Upvotes: 0

AxelH
AxelH

Reputation: 14572

My solution would be a bit simpler.

First, I would not use those arrays but one 2D array like :

static char[][] keyboard = {
    {'a','b','c'},     //2
    {'d','e','f'},     //3
    {'g','h','i'},     //4
    {'j','k','l'},     //5
    {'m','n','o'},     //6
    {'p','q','r','s'}, //7
    {'t','u','v'},     //8
    {'w','x','y','z'}  //9
};

Then, from this, I would loop on every character of the input you have. For each character, I would search on which array it is. The value you need is the index + 2. So using a simple for-loop on keyboard, you can find where is the character and print the value you want. There is exception for numeric, space and symbol of course.

for each character in input
    if character is numeric
        output ( toNumeric ( character ) )
    else
        index = 0
        while character not found
            if character in array[index]
               output ( index + 2 )
        index++

For more code, well, you need to give more information because you need to work a bit too ;)

Upvotes: 1

kiran
kiran

Reputation: 1

public static void main(String[] args) {
    String[] dialTwo = { "a", "b", "c" };
    String[] dialThree = { "d", "e", "f" };
    String[] dialFour = { "g", "h", "i" };
    String[] dialFive = { "j", "k", "l" };
    String[] dialSix = { "m", "n", "o" };
    String[] dialSeven = { "p", "q", "r", "s" };
    String[] dialEight = { "t", "u", "v" };
    String[] dialNine = { "w", "x", "y", "z" };

    Scanner in = new Scanner(System.in);

    System.out.print("Enter a phone number: ");
    String phoneInput = in.next();
    char[] inputToArray = phoneInput.toCharArray();

    int i = 0;
    while (!phoneInput.matches("^[a-zA-Z0-9]*$")) { // Used to check if any
                                                    // special character is
                                                    // enter in phone number
        System.out.println("Not a valid number. Try agian.");
        phoneInput = in.next();
    }

    List<String> one = (List) Arrays.asList(dialTwo);
    // for converting array into list so that we can use contains method
    // which is not //available in array
    List<String> two = (List) Arrays.asList(dialThree);
    List<String> three = (List) Arrays.asList(dialFour);
    List<String> four = (List) Arrays.asList(dialFive);
    List<String> five = (List) Arrays.asList(dialSix);
    List<String> six = (List) Arrays.asList(dialSeven);
    List<String> seven = (List) Arrays.asList(dialEight);
    List<String> eight = (List) Arrays.asList(dialNine);

    while (i < inputToArray.length) {
        if (inputToArray[i] >= 48 && inputToArray[i] <= 57) {
            // for numeric characters

            System.out.print(inputToArray[i]);
        } else if (one.contains(String.valueOf(inputToArray[i]).toLowerCase()))
        /*
         * searches given character by converting it into lower case in case
         * of capital letters
         */
        {
            System.out.print(1);
        } else if (two.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(2);
        } else if (three.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(3);
        } else if (four.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(4);
        } else if (five.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(5);
        } else if (six.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(6);
        } else if (seven.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(7);
        } else if (eight.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(8);
        }
        i++;// counter variable for counting number of chars entered
    }
}

Upvotes: 0

Tosh
Tosh

Reputation: 71

A simple way to do that is to map a function to use map

inputToArray.stream().map(/*some function*/).toArray();
private void int /*your function*/(char c){...}

A little rusty on Java so can't claim the syntax is correct but basically map a function that takes a char and returns your desired int to your array. After that all you have to do is write the actual function you are mapping.

There's also a number of ways you could just parse the string returned by next as there doesn't seem to be any particular reason in your code for the conversion to a char array

It should also be mentioned that it is rather inefficient to have arrays of 1 length strings for no specific reason. You could easily use strings instead

Upvotes: 0

user1211
user1211

Reputation: 1515

You can use Collections instead of String[]. Probably map would be good. But, since you are using String[] following code should help:

for (int i = 0; i < inputToArray.length; i++) {
                if (Arrays.asList(dialTwo).contains(inputToArray[i]))
                    inputToArray[i]=2;
            ...

            }

You need to fill the ... part with other if else conditions where you check for inputToArray[i] with other arrays and replace accordingly.

Upvotes: 0

Related Questions