簡體   English   中英

Java:在電話鍵盤上將字母轉換為數字

[英]Java: Converting letters to digits on a phone keypad

我正在為一個班級分配作業,我需要將用戶輸入的字母轉換為電話上的數字。 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語句中。

在if塊上,您的第一個條件是if (y>=65 || y<=67) 讓我們打開一點:

IF ( y >= 65 ) OR ( y <= 67 )

看到問題了嗎? 由於您已編寫OR,因此整個語句將始終為true :對於任何int y,y都必須大於65或小於67。我懷疑您打算編寫AND( && )。

您的條件有誤,請更改|| &&

if (y>=65 && y<=67) ...

並像這樣糾正所有條件。

有例子(y>=65 || y<=67) 這意味着該條件始終為true ,因為任何y始終大於或等於65, 或者小於或等於67(難以解釋)。 如果要檢查,如果同時滿足兩個條件,則必須使用&&

您的第一個條件是if (y>=65 || y<=67)並且對於任何字符,如果滿足這兩個條件中的任何一個,它將打印x+"'s corrosponding digit is " + 2並且從不檢查其他任何一個else if條件。 您需要替換|| 在所有情況下都可以使用&&運算符。

為什么不這樣:

char x = input.next().charAt(0);
x = Character.toUpperCase(x);
int digit = 0;
switch (x ) {
   case 'A': case 'B': case 'C':
      digit = 1;
      break;
   case 'D': case'E': case 'F':
      digit = 2;
      break;
   //etc.
   default:
      break;
}
if ( digit < 1 ) {
   System.out.println( "The letter " + x + " is not on a phone pad" );
} else {
   System.out.println( "x + "'s corrosponding digit is " + digit);
}

請注意,某些電話可能會使用不同的字母組合。 例如,有些電話使用“ PQRS”表示7,有些使用“ PRS”,省略了Q。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM