简体   繁体   English

从Java的String输入返回数字

[英]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.). 在这里,我必须将用户输入的字符串转换为大写字母,然后使用电话键盘系统(2 = ABC等)将那些大写字母转换为数字。

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. 要获取一个char的数字,您可能应该反过来进行数组处理。 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. keys数组放入类的成员变量中也是一个好主意,这样您就不必在每次调用时都对其进行初始化。

As for the output/conversion, I suggest you have a look at java.lang.System class. 至于输出/转换,建议您看一下java.lang.System类。 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). 还要注意,您尚未将字符串转换为大写字母-并没有检查输入的有效性(它是仅由26个字母组成的字符串)。

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 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. 最简单的方法是在String类中使用indexOf()方法,如果所引用的字符串中存在子字符串,则返回值> -1。

So "ABC".indexOf("A") would return 0, "ABC".indexOf("C") would return 2, and "ABC".indexOf("D") would return -1; 因此, "ABC".indexOf("A")将返回0, "ABC".indexOf("C")将返回2,而"ABC".indexOf("D")将返回-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. 使用for循环寻址键盘数组中的每个字符串,并使用上述方法检查输入的字符是否映射到当前选择。

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<String, Integer>如下所示:

 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 ). 请注意,我在这里使用了自动装箱: char get自动转换为Character ,反之亦然(例如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. 在您的getNumber函数中,您似乎想要遍历键盘阵列。 The logical question to ask is: "At each step of the for loop, what are you looking for and are you done?". 要提出的逻辑问题是:“在for循环的每个步骤中,您正在寻找什么并且已经完成?”。 For example, suppose your uppecaseLetter is 'E'. 例如,假设您的uppecaseLetter为'E'。 Then going through the steps: 然后执行以下步骤:

first, (i=0), you don't know anything since Keypad[0] is unused. 首先,(i = 0),您什么都不知道,因为未使用键盘[0]。

next, (i=1). 接下来,(i = 1)。 Still nothing, since Keypad[1] is unused 仍然没有,因为未使用键盘[1]

next, (i=2). 接下来,(i = 2)。 Keypad[2] = "ABC" but the letter is E (and it isn't in "ABC") so nothing here Keypad [2] =“ ABC”,但字母为E(并且不在“ ABC”中),因此此处无内容

next, (i=3). 接下来,(i = 3)。 Keypad[3] = "DEF" letter E is here, so you know you could return i (i=3) here 键盘[3] =“ DEF”字母E在这里,所以您知道您可以在此处返回i(i = 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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