Here is what I’m suppose to accomplish:
Write a program that stimulates a bean machine Your program should prompt the user to enter the number of balls and the number of slots in the machine. Simulate the falling of each ball by printing its path.
EX.
Enter the number of balls: 5
Enter the number of slots: 7LRLRLRL
RRLRLLL
LLRRLLR
LRLLRLR
RRRLRRL
_ _ 0
_ _ 0
0 0 0
Here is my code so far:
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]); } }
There are a few things that I’m having problems with:
- In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?
- How can I print the number ‘balls’ that the user entered in the pattern as shown above?
- Are there any other problems with my code?
Well, for starters, I’m getting a consistent
ArrayIndexOutOfBoundsExceptionon the linedirection[slots] = 'L';(or'R'). That’s becausedirectionis always of length 0, since you initialized it toslotswhenslotswas 0. Move the lineto after
slotsis input.Next, you always assign the ‘L’ or ‘R’ to the position immediately after the end of the array. That’s another reason for the
ArrayIndexOutOfBoundsExceptionI was getting. Change the assignment toNext, you don’t reset
iafter thewhileloop. So the path is calculated only for the first ball and then reused for all the others. I would make it aforloop instead, like this:Finally, as others have said, you should be using a loop to print out the path. You know how long the
directionarray is (it’sdirection.length, if you didn’t know), so you can just loop through it and print out each letter.Once you’ve made these changes, your program should work (edit: except that it doesn’t keep track of which slot each ball ends up in). It will still have some room for improvement, but finding those things is part of the fun–isn’t it?