Introduction to Java Programming编程题9.7<将字符串中的字符转换为数字>

本博客介绍了一个使用Java实现的程序,该程序将输入的字母字符串转换为对应的电话号码数字。程序通过定义一个字符到数字的映射表,并遍历输入字符串中的每个字符来完成转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
Enter a string: 1-800-Flowers
1-800-3569377
Enter a string: 1800flowers
18003569377
 */

import java.util.Scanner;

public class CountLetter {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = input.nextLine();

        char n;
        for (int i = 0; i < str.length(); i++) {
            if (Character.isLetter(str.charAt(i))) {
                n = getNumber(Character.toUpperCase(str.charAt(i)));
                str = str.replace(str.charAt(i), n);
            }
        }
        System.out.println(str);
    }

    public static char getNumber(char up) {
        char digit = 'A';
        switch (up) {
            case 'A':
            case 'B':
            case 'C':
                digit = '2';
                break;
            case 'D':
            case 'E':
            case 'F':
                digit = '3';
                break;
            case 'G':
            case 'H':
            case 'I':
                digit = '4';
                break;
            case 'J':
            case 'K':
            case 'L':
                digit = '5';
                break;
            case 'M':
            case 'N':
            case 'O':
                digit = '6';
                break;
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
                digit = '7';
                break;
            case 'T':
            case 'U':
            case 'V':
                digit = '8';
                break;
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
                digit = '9';
        }

        return digit;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值