2017-05-19 148 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); 

}