2014-01-30 40 views
0
import java.util.Scanner; 
public class Selection 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     char key = 'A'; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter a letter to find the corresponding digit on a cellphone: "); 
     int digit; 
     switch (key) { 

      case 'A' & 'B' & 'C': digit = 2; 
       break; 

      case 'D' & 'E' & 'F': digit = 3; 
       break; 

      case 'G' & 'H' & 'I': digit = 4; 
       break; 

      case 'J' & 'K' & 'L': digit = 5; 
       break; 

      case 'M' & 'N' & '0': digit = 6; 
       break; 

      case 'P' & 'Q' & 'R' & 'S': digit = 7; 
       break; 

      case 'T' & 'U' & 'V': digit = 8; 
       break; 

      case 'W' & 'X' & 'Y' & 'Z': digit = 9; 
       break; 

      default: System.out.println("There is no matching digit for that character."); 

      System.out.println("The letter " + key + " corresponds to the number " + digit + " on a  cellphone."); 
     } 
    } 
} 

這是我到目前爲止。基本上,我需要製作一些需要按字母順序輸入字母的內容,並在手機上顯示與該字母相對應的數字,只接受大寫字母,並在輸入其他內容時顯示錯誤。我想要的最後一件事是有人爲我做,我只是想要指導。我不斷收到一個重複的案例錯誤

+3

您認爲'&'做什麼? –

+0

噓我現在看到;) – suislaluna

回答

2

我猜你的意思

case 'A': 
case 'B': 
case 'C': domSomethingHere(); break 

case 'E': 
case 'F': 
case 'G': domSomethingHere(); break 
+0

啊,好的。那麼這種方法甚至會對我所期待的最好? – suislaluna

3

&運營商沒有做什麼你想在這裏。它是按位進行的 - 並且對角色中的位進行執行,並且其中一些情況的結果是相同的。根據我的IDE,

'A' & 'B' & 'C' => '@' 
'G' & 'H' & 'I' => '@' 
'P' & 'Q' & 'R' & 'S' => 'P' 
'W' & 'X' & 'Y' & 'Z' => 'P' 

即使有沒有重複的情況下,你的代碼是行不通的,因爲你有你沒想到的字符的情況。要爲多個案例執行相同的代碼,請嘗試以下操作:

case A: 
case B: 
case C: 
    digit = 2; 
    break; 
case D: 
case E: 
case F: 
    digit = 3; 
    break; 
// and so on 
+0

謝謝!我會再玩一些。 – suislaluna

相關問題