2016-02-29 131 views
-1

我正在爲班級分配工作,我需要將一封信的用戶輸入信息轉換爲電話號碼。像A = 2或K = 5一樣。我將用戶輸入轉換爲大寫,然後轉換爲ASCII。我使用的ASCII爲我的if/else和它編譯和作品,但始終打印Java:將字母轉換爲電話鍵盤上的數字。

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

不管信我輸入,也是最後一行

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

不起作用,它只是打印出數字是2,x是我輸入的東西。

import java.util.Scanner; 

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); 






} 

} 
+0

這不是一個MCVE。 – Raedwald

回答

1

更換||與& &在你的if else語句中。

1

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

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

您是否看到這個問題?既然你寫了一個OR,整個聲明總是會計算爲true:對於任何int y,y必須大於65或小於67.我懷疑你打算寫一個AND(&&)。

1

你有錯的條件下,改變||&&

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

,正確的一樣,所有條件。

舉例(y>=65 || y<=67)。這意味着條件總是爲true,因爲任何y始終大於或等於65 小於或等於67(難以解釋)。如果要檢查,如果這兩個條件同時是真實的,你必須使用&&

1

你的第一個條件是if (y>=65 || y<=67)和任何字符,如果任何這些2個條件滿足時,將打印x+"'s corrosponding digit is " + 2和從來不檢查任何的其他else if條件。您需要在所有條件下將||運營商更換爲&&運營商。

1

爲什麼不一樣的東西:

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.