3

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.

user1211
  • 1,507
  • 1
  • 18
  • 27
  • Any specific reason you are using String []? Anyways, you need to use a for loop that iterates over the char array. Check each string[] contains that specific char and replace the char accordingly. – user1211 Dec 06 '16 at 03:56
  • @user1211 thanks for your reply. Do you mind going through how to do that? I'm a little confused on how to use a for loop to cycle through the string. And as for the String [], im not too sure... should i use char []? – guccimanilla Dec 06 '16 at 04:04
  • Possible duplicate of [stuck on a java phone number word generator](http://stackoverflow.com/questions/19793247/stuck-on-a-java-phone-number-word-generator) – Igoranze Dec 06 '16 at 08:53
  • Well, from what I see, you have your arrays of value (could use one String[][]). And you should have a phoneInput values. But what have you tried ? Your teacher might prefer a code coming for you (and a bit updated by the SO community). – AxelH Dec 06 '16 at 10:42
  • PS : `CFG` should output `123` or `234` ? – AxelH Dec 06 '16 at 11:19
  • Do mark the answer that you find the most useful as 'Accepted'. It will help others also who happen to refer your question. – Dhaval Simaria Dec 19 '16 at 13:49

5 Answers5

1

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 ;)

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • Thank you for your answer, but this is still really confusing to me, guess I'll have to talk to the teacher – guccimanilla Dec 06 '16 at 15:02
  • @guccimanilla what part? I tried to stay on an analysis answer to let you understand and try this yourself, this will be how you will learn. But I can still explain or guide you more. – AxelH Dec 06 '16 at 18:59
0

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.

user1211
  • 1,507
  • 1
  • 18
  • 27
0

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

Tosh
  • 71
  • 7
0

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.

Dhaval Simaria
  • 1,886
  • 3
  • 28
  • 36
  • Please explain the code you have post, "code only" answer are not helpful. – AxelH Dec 06 '16 at 10:40
  • @AxelH edited the answer to include the explanation in comments. – Dhaval Simaria Dec 06 '16 at 10:54
  • Well, you could have put those outside the code ;) and the numeric value are wrong, a-c = 2, not 1. – AxelH Dec 06 '16 at 11:01
  • @AxelH well I've not done calculations there. `["a-cA-C"]` is regex which will identity one occurrence of alphabet at a time and replace it with "1". Same goes for other values as well. – Dhaval Simaria Dec 06 '16 at 11:07
  • @AxelH as far as explanation is considered, code is best explained through comments. – Dhaval Simaria Dec 06 '16 at 11:08
  • I know that, you might be too young to have know cellular keyboard ;) but [a-c] ison key 2, [D-F] on key 3, ... see the name of OP arrays. You need to increment the values you are using. For the comments, yes in source code, on SO, you can use text ... but this was just a simple observation about that. – AxelH Dec 06 '16 at 11:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129896/discussion-between-dhaval-simaria-and-axelh). – Dhaval Simaria Dec 06 '16 at 11:14
0
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
    }
}
AxelH
  • 14,325
  • 2
  • 25
  • 55
kiran
  • 1
  • 1