2013-03-29 44 views
0

打印,請參閱以下內容:開關case語句從我是一個初學者鍵盤

public class CaseBreak { 
    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 
     int key = 1; 
     int dob = keyboard.nextInt(); 
     switch(dob + key + 1) 
     { 
     case 1: 
      System.out.println("First switch"); 
      break; 
     case 2: 
      System.out.println("Second switch"); 
      break; 
     case 3: 
      System.out.println("Third switch"); 
      break;  
     case 4: 
      System.out.println("Fourth switch"); 
      break;  
     case 5: 
      System.out.println("Fifth switch"); 
      break;  
     case 6: 
      System.out.println("Sixth switch"); 
      break;  
     case 7: 
      System.out.println("Seventh switch"); 
      break;  
     default: 
      System.out.println("Out of Switch! there is no"); 
     } 
    } 
} 

在接下來的一切都運行良好。但是我想打印這個數字以及鍵盤輸入超出大小時調用的默認語句。像ex-number 7這樣的東西進入默認狀態,我得到「Out of Switch!沒有」。我只是希望它也應該顯示數字之後的語句(Out of Switch!there is no 7)

+4

'System.out.println(「Out of Switch !! there is no」+(dob + key + 1)) ;' –

回答

1

您的號碼是dob + key + 1。你爲什麼不打印它?

:圍繞DOB +鍵+1()因爲+這是非常重要的是連接運算符和要編譯告訴總和的數字。

default: 
    System.out.println("Out of Switch!! there is no " + (dob + key + 1)); 

如果你寫這樣的:

default: 
     System.out.println("Out of Switch!! there is no " + dob + key + 1); 

然後你會得到作爲輸出:(說DOB是1,密鑰2)

輸出開關的! !沒有121

但是,如果你用圓括號包圍它,那麼你會得到三個整數的實際總和。

4

您可以使用+將字符串和數字一起添加,理想情況下,您應該將dob + key + 1存儲到變量中,因此您只能計算一次。

int i = dob + key + 1 
switch(i) 
{ 
    // ... 
    default: 
     System.out.println("Out of Switch!! there is no" + i); 
} 
0
default: 
System.out.println("Out of Switch!! there is no"+dob); 

我認爲這是你在找什麼。它會告訴輸入的是哪一個數字,並與默認的sop中的語句一起打印。這是當你想看到你輸入的數字。如果你想看到+1這個數字在你的交換機上完成,那麼做System.out.println("Out of Switch!! there is no"+dob+key+1);