2013-11-23 106 views
2

我希望程序为循环的每次迭代不断增加局。 当我运行该程序时,它正在这样做,但它显示的值不正确。Java:while循环和数组递增

例如: 你滚... 4 你总该安监局至今6

第二行应该显示,” ......至今4"

这是我现在的代码如下:

import java.util.Random; 
import javax.swing.*; 

public class shortSix { 

    public static void main(String[] args) { 
     diceGame(); 
}//ENDS MAIN 
    public static void diceGame() 
    { 
     final int[] innings = new int[1]; 
     innings[0] = 0; 

     Random dice = new Random(); 
     int diceRoll = dice.nextInt(6) + 1; 

     while (diceRoll != 5) 
     { 
      System.out.println("You rolled..." + diceRoll); 
      diceRoll = dice.nextInt(6) + 1; 
      innings[0] =+ diceRoll; 
      System.out.println("Your total for this innings so far is " + innings[0]); 

      String userDeclare = JOptionPane.showInputDialog(null, "Do you wish to declare?"); 
      if (userDeclare.equals("yes")) 
      { 
       System.exit(0); 
      } 

     } 
    }//ENDS diceGame 
}//ENDS class shortSix 
+0

为什么'局'被定义为'final'? –

+0

我应该使用最后一个变量来存储这个问题的值 – AbbenGabben

+0

'innings [0] = + diceRoll'中'= +'的用途是什么? – Pshemo

回答

4

问题是您没有在第一次滚动后更新阵列记录。你得到了int diceRoll = ...,然后你再给随机值赋予变量并在第二次滚动后添加分数。第一个结果被忽略。所有你需要做的是改变

diceRoll = dice.nextInt(6) + 1; 
innings[0] =+ diceRoll; 

innings[0] =+ diceRoll; 
diceRoll = dice.nextInt(6) + 1; 
+0

我会将此标记为已接受的答案,但是我必须等待另外7分钟。我改变了顺序,并修改了= +到+ = – AbbenGabben

1

您打印

System.out.println("Your total for this innings so far is " + innings[0]); 

这导致制造一个新的随机数之前调用

diceRoll = dice.nextInt(6) + 1; 

,并是问题。

2

有两个问题:

  1. = +而不是+ =前操作的第二的println
  2. 令很奇怪。您首先打印当前值,然后更新它,然后只增加计数器并打印摘要。可能你想移动diceRoll =骰子......在第二次打印之后
+0

啊,这是有道理的。我现在改变了它,它工作正常。 – AbbenGabben