Java:将电话键盘上的字母转换为数字

标签 java if-statement boolean logical-operators

我正在为一门类(class)做作业,其中我需要将用户输入的字母转换为手机上的数字。例如 A=2K=5。我将用户输入转换为大写,然后转换为 ASCII。我在 if/else 中使用 ASCII,它可以编译并工作,但总是打印

System.out.println (x+"'s corrosponding digit is " + 2); 

无论我输入什么字母,最后一行也是如此

else System.err.println("invalid char " + x);

不起作用,它只是打印出数字是2,其中x是我输入的内容。

public class Phone {

    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println ("Please enter a letter from A-Z.");
        char x = input.next().charAt(0);
        x = Character.toUpperCase(x);
        int y = x;
        System.out.println ("You entered the letter " + x);

        if (y>=65 || y<=67)
            System.out.println (x+"'s corrosponding digit is " + 2);
        else if (y>=68 || y<=70)
            System.out.println (x+"'s corrosponding digit is " + 3);
        else if (y>=71 || y<=73)
            System.out.println (x+"'s corrosponding digit is " + 4);
        else if (y>=74 || y<=76)
            System.out.println (x+"'s corrosponding digit is " + 5);
        else if (y>=77 || y<=79)
            System.out.println (x+"'s corrosponding digit is " + 6);
        else if (y>=80 || y<=83)
            System.out.println (x+"'s corrosponding digit is " + 7);
        else if (y>=84 || y<=86)
            System.out.println (x+"'s corrosponding digit is " + 8);
        else if (y>=87 || y<=90)
            System.out.println (x+"'s corrosponding digit is " + 9);
        else System.err.println("invalid char " + x);           
    }   
}   

最佳答案

替换||在 if else 语句中使用 &&。

关于Java:将电话键盘上的字母转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711018/

相关文章:

java - 使用enable ReceiveTimeout后读取流

PHP 在 if 语句中组合 boolean 运算符(AND、OR)

java - 检查 boolean 值是否已在 Java 中更改

c++ - 按位与函数在 C++ 中返回 bool

java - 使用相机拍照并将其保存到图库

java - 构造函数 SimpleCommandBus() 不可见 -Axon

java - 强制序列化不可序列化的 Java 对象?

javascript - 如果 Else 和 Javascript 我缺少什么?

perl - perl-关闭if语句时语法错误

swift - 为什么 boolean 类型不能在swift中进行按位运算