2017-05-19 111 views
1

我不知道如何給這個問題的標題,但基本上這是我的二十一點程序的一部分。另外,由於我不知道如何標題,所以我不確定如何查看它,這就是我在這裏問的原因。所以我說當用戶輸入1或11作爲ace值時,如果他們輸入了1或11以外的值,它會再次要求用戶輸入1或11.在我的程序中,一切正常,除非用戶進入1,那麼它只是再次提出問題。應該只又問如果輸入不等於1或11的程序這裏是我的代碼,我確信它總是給用於測試目的的王牌:Java嵌套如果語句 - 或比較!=

String card1="A"; 
int total=0; 
Scanner input_var=new Scanner(System.in); 
if (card1=="A"){ 
    System.out.println("Do you want a 1 or 11 for the Ace?: "); 
    int player_ace_selection=input_var.nextInt(); 
    if ((1|11)!=(player_ace_selection)){ 
     System.out.println("Please enter a 1 or 11: "); 
     int new_selection=input_var.nextInt(); 
     total=total + new_selection; 
    } 
    else { 
     total=total + player_ace_selection; 
    } 
} 
System.out.println(total); 

在此先感謝。

+0

提示:'.nextInt()''VS .nextLine' - >先不讀新行'\ N' – Yahya

+0

沒有簡寫形式'或',你正在做一個按位或在'(1 | 11)!'(player_ace_selection)''1'和'11'處' –

+0

'card1 ==「A」'這裏不是唯一的問題,它不是主要的問題。投票重新開放。 – dasblinkenlight

回答

1

而不是If語句,請嘗試一個while循環。 while循環確保程序等待用戶選擇正確的答案。你的邏輯操作也犯了一個錯誤。在這種情況下使用「OR」的正確方法是使用'||'分別將您的用戶輸入與'1'和'11'進行比較。

String card1="A"; 
    int total=0; 
    Scanner input_var=new Scanner(System.in); 
    if (card1.equals("A")){ 
     System.out.println("Do you want a 1 or 11 for the Ace?: "); 
     int player_ace_selection=input_var.nextInt(); 

     while(player_ace_selection != 1 && player_ace_selection != 11){ 
      System.out.println("Do you want a 1 or 11 for the Ace?: "); 
      player_ace_selection = input_var.nextInt();     
     } 
     total += player_ace_selection; 
    } 

    System.out.println(total); 
+1

你的代碼中有一個很大的錯誤,while循環永遠不會停止! – Yahya

+0

什麼條件可以滿足你的'while'循環? –

+0

感謝您指出這一點 –

3

表達(1|11)使用二進制OR,其產生11

11 = 01001 
    1 = 00001 
(11|1) = 01001 

因此,比較相同11!=player_ace_selection

你應該改變的代碼使用邏輯OR,即

if (1!=player_ace_selection && 11!=player_ace_selection) { 
    ... 
} 

另外,您需要修復card1 == "A"比較card1.equals("A")

+0

假設一個很好的解釋。 –

0

您的代碼存在一些問題,請考慮此示例並與您的代碼進行比較。

String card1="A"; 
int total=0; 
Scanner input_var=new Scanner(System.in); 
if (card1.equals("A")){ // compare the content not the reference (==) 
    System.out.println("Do you want a 1 or 11 for the Ace?: "); 
    try{ // wrap with try-catch block 
     int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input 
     if ((player_ace_selection!=1)&&(player_ace_selection!=11)){ 
      System.out.println("Please enter a 1 or 11: "); 
      try{ 
       int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input 
       total=total + new_selection; 
      }catch(NumberFormatException e){ 
        // do something to catch the error 
      } 
     } 
     else { 
      total=total + player_ace_selection; 

     } 

    }catch(NumberFormatException e){ 
      // do something to catch the error 
    } 
    System.out.println(total); 

}