简体   繁体   中英

Return numbers from String input, Java

I am kind of stumped here and have been trying to figure this out for some time. This is homework, although I want to learn to code regardless. Here I have to convert the string input by the user to uppercase letters, then those uppercase letters to numbers using the phone keypad system(2 = ABC etc.).

I have gotten this far but am unsure as to what my next step should be. Any ideas are greatly appreciated, thanks in advance.

package chapter_9;

import java.util.Scanner;

public class Nine_Seven {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String s = input.next();

        // unsure what to do here, know i need some sort of output/return
        // statement
    }

    public static int getNumber(char uppercaseLetter) {
        String[] Keypad = new String[10];
        Keypad[2] = "ABC";
        Keypad[3] = "DEF";
        Keypad[4] = "GHI";
        Keypad[5] = "JKL";
        Keypad[6] = "MNO";
        Keypad[7] = "PQRS";
        Keypad[8] = "TUV";
        Keypad[9] = "WXYZ";

        for (int i = 0; i < Keypad.length; i++) {
            // unsure what to do here
        }

        return (uppercaseLetter);
    }
}

To get the number for a char, you should probably do your array the other way around. You method could look like this:

public static int getNumber(char uppercaseLetter) {
    int[] keys = {2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};
    return keys[(int)uppercaseLetter - 65];  //65 is the code for 'A'
}

It may also be a good idea to pull the keys array into a member variable for the class so that you don't initialise it on every call.

As for the output/conversion, I suggest you have a look at java.lang.System class. Also note that you haven't converted the string to uppercase - and are not checking for the validity of input (that it's a string made from just the 26 letters).

Here is the whole program.

public class  Mobile Key Pad{

public static void main(String[] args) {

         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a string: ");
         String s = sc.next();    
         char ch[]=s.toCharArray();
         int n[]=new int[s.length()];

         for(int i=0;i<ch.length;i++)    
         {
            n[i]= getNumber(ch[i]);
            System.out.print(n[i]);
         }
    }

    public static int getNumber(char uppercaseLetter) {
        String[] Keypad = new String[10];
        Keypad[2] = "ABC";
        Keypad[3] = "DEF";
        Keypad[4] = "GHI";
        Keypad[5] = "JKL";
        Keypad[6] = "MNO";
        Keypad[7] = "PQRS";
        Keypad[8] = "TUV";
        Keypad[9] = "WXYZ";

            for(int i = 2;i < Keypad.length;i++) 
            {
                if(Keypad[i].indexOf(uppercaseLetter) != -1) 
                {
                    return i;
                }  
            }
        return (uppercaseLetter);     
  }
}

String.IndexOf

// unsure what to do here

can be:

for(int i = 2;i < Keypad.length;i++) {

    if(Keypad[i].indexOf(uppercaseLetter) != -1) 
    {
        return i;
    }  

}

There are many other, better ways to accomplish this, but this is one way.

查看“ Map ,看看是否有任何想法。

    -

  1. List item

// unsure what to do here, know i need some sort of output/return

// statement

     char ch[]=s.toCharArray();


     int n[]=new int[s.length()];


     for(int i=0;i<ch.length;i++)


     {

        n[i]= getNumber(ch[i]);

        System.out.print(n[i]);


     }

A complete program for this question.

import java.util.Scanner;

public class PhonePad {

public static void main(String[] args) {
    System.out.println("Mobile Phone key  Pad ( Considering 2 to 9 as keys)");
    System.out.println("Enter the Switch Number"
            + " 1st and no of times it got pressed "
            + "\n Press any word to exit");
    StringBuilder str = new StringBuilder();

    try {
        while (true) {
            Scanner s = new Scanner(System.in);
            int swNum = s.nextInt();
            int no = s.nextInt();
            if ((swNum > 9 ||swNum <2) ||(no > 4||no <1)) 
                break;
            else if ((swNum>7&&swNum<10) || (swNum >1 &&swNum<7) 
                    || (swNum ==7 && no ==4)){ // 7  has PQRS
                if(swNum > 7){
                    no++;
                }
                int temp = swNum * 3 + (no - 1) + 59;
                System.out.println("Entered char is "+(char) temp);
                str.append((char) temp);
            } else
                break;
        }
    } catch (Exception e) {
        System.out.println("Exiting terminal");
    } finally {
        System.out.println("Thanks for using my Keypad... visit again");
        System.out.println("Entered keyword is " + str.toString());
    }

}

}

Your requirement seems to be to find the entered character in your Keypad array.

The naive way to do this is to use the indexOf() method in the String class, which returns a value > -1 if a substring exists in the referenced string.

So "ABC".indexOf("A") would return 0, "ABC".indexOf("C") would return 2, and "ABC".indexOf("D") would return -1;

Use the for loop to address every string in the Keypad array, and use the above method to check whether the entered character maps to the current selection.

First of all, I'd not put the mapping into the method but into the class itself. Next, you might try and use a Map<String, Integer> like this:

 Map<Character, Integer> charToNum = new HashMap<Character, Integer>();
 charToNum.put('A', 2);
 charToNum.put('B', 2);
 charToNum.put('C', 2);
 charToNum.put('D', 3);
 ...

If you then need to get the number for a character, just call:

public static int getNumber(char uppercaseLetter) {
   return charToNum.get(uppercaseLetter);
}

Note that I make use of auto(un)boxing here: char get's automatically converted to Character and vice versa (like int <-> Integer ). That's why using a map works here.

In your getNumber function, it looks like you want to go through your Keypad array. The logical question to ask is: "At each step of the for loop, what are you looking for and are you done?". For example, suppose your uppecaseLetter is 'E'. Then going through the steps:

first, (i=0), you don't know anything since Keypad[0] is unused.

next, (i=1). Still nothing, since Keypad[1] is unused

next, (i=2). Keypad[2] = "ABC" but the letter is E (and it isn't in "ABC") so nothing here

next, (i=3). Keypad[3] = "DEF" letter E is here, so you know you could return i (i=3) here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM