以下是我应该完成的任务:
编写一个刺激豆机的程序,您的程序应该提示用户输入机器中的球数和插槽数。通过打印每个球的路径来模拟每个球的下落。 EX.Enter球数:5加入槽数:7 RRLRLLL LLRRLLRLRLLRLR RRRLRRL_ _ 0_ _0 0 0 0
到目前为止,我的代码如下:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int balls=0;
int slots=0;
char [] direction= new char [slots];
int slot=0;
int i=0;
int path=0;
balls= Integer.parseInt(JOptionPane.showInputDialog("Enter" +
" the number of balls to be dropped:"));
slots= Integer.parseInt (JOptionPane.showInputDialog("Enter " +
"the number of slots:"));
for (int j=1;j<=balls;j++){
while(i<slots){
path= (int)(Math.random()*100);
if (path <50){
direction [slots]='L';
}
else{
direction [slots]='R';
}
i++;
slot++;
}
System.out.println("The pathway is" +direction[0]+direction[1]+direction[2]+direction[3]+direction[4]);
}
}有几件事我有问题:
发布于 2009-03-26 16:51:03
首先,我在行ArrayIndexOutOfBoundsException (或'R')上得到了一个一致的direction[slots] = 'L';。这是因为direction总是长度为0,因为您在slots为0时将其初始化为slots。移动线
char [] direction= new char [slots];在slots之后输入。
接下来,总是在数组结束后立即将'L‘或'R’分配给位置。这也是我得到ArrayIndexOutOfBoundsException的另一个原因。将任务更改为
direction[i] = 'L'; // or 'R'接下来,不要在i循环之后重置while。因此,该路径只为第一个球计算,然后对所有其他球重复使用。我会把它变成一个for循环,如下所示:
for (i = 0; i < slots; i++) {
// your code here (make sure you don't change i inside the loop)
}最后,正如其他人所说的,您应该使用一个循环来打印路径。您知道direction数组的长度(如果您不知道的话,它是direction.length ),所以您可以循环遍历它并打印出每个字母。
一旦您做了这些更改,您的程序就会正常工作(编辑:,只是它不跟踪每个球在哪个位置结束)。它仍然有一些改进的空间,但找到那些东西是乐趣的一部分--不是吗?
发布于 2009-03-26 16:52:43
在我的代码的最后一行中,我尝试打印路径,我必须基本上猜出用户选择的插槽的数量。有更好的方法打印这个吗?
使用for循环,并使用System.out.print(),这样您就不会在每一步之后得到一个新行。
如何打印用户按上面所示的模式输入的数字“球”?
对于每个插槽,您需要记录在该插槽中的球数,以及任何插槽的最大值。给定这两个值,您可以在每个插槽上循环,并使用嵌套循环打印“_”或“0”适当的次数。
我的代码还有其他问题吗?
你似乎只是打印最后一个球掉下来的路径,而不是每一个球,但这可能只是你的缩进是不确定的。发布正确的格式,完整的代码。
示例输出似乎是从控制台读取输入,而不是使用swing。
你说变量太早了。最好在第一次使用时声明变量,如果它们不更改,则标记为final。如果你有:
final int slots= Integer.parseInt (...而不是
int slots = 0;
...
slots= Integer.parseInt (...那么编译器至少会捕捉到一个bug。
发布于 2009-03-26 16:56:37
一些答案:
for loop。System.out.print或System.out.printf会有帮助。System.out.println("Number of balls: "+ something that makes an int into a string (那会是什么?)Math.random()的结果放入int中?如果使用:如果(Math.random()< 0.5) { //做某事}{ //做相反的},会发生什么?https://stackoverflow.com/questions/686588
复制相似问题