English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

preferably by creating a class which generates random numbers and then calling on it in the main method......The program below is in the main method.

//Programming the LuckyDip of the first line to produce 6 random numbers
void LuckyDip1_actionPerformed(ActionEvent e) {
int[] array = new int [6];
int[] tmp = new int[1];
int count = 0;
luckyNum = 1 + (int)(Math.random()*49);
array [count] = luckyNum;

count++;
luckyNum = 1 + (int)(Math.random()*49);
array [count] =luckyNum;

count++;
luckyNum = 1 + (int)(Math.random()*49);
array [count] =luckyNum;

for (int i=array.length; i>1;i++)
{
for (int j=1; j {
if (array[j-1]>array[j])
{
int temp=array[j-1];
array[j-1]=array[j];
array[j]=temp;
}
}

jTextField1.setText(""+array[0]

2007-07-26 02:06:15 · 1 answers · asked by Night_nurse 2 in Computers & Internet Programming & Design

1 answers

There are several things you can do:

(1) ======================
This code:
luckyNum = 1 + (int)(Math.random()*49);
array [count] = luckyNum;
... is repeated three times.

Why not write it as a loop instead? Why store the value in luckyNum just to move it into the array? And why create an array of length 6, when you only fill out the first three values? I'm assuming it was meant to be six times.

(2) ======================
You don't seem to use int tmp[] so you can delete that declaration.

(3) ======================
You don't have to manually sort the array using a bubble-sort. You can just do this:

java.util.Arrays.sort(array);

... which knows how to sort an array of int. It sorts the array in-place.

(4) ======================
Why manually concatenate all the output into the string, when you can use a loop to put it together?

Yahoo Answers truncated that line, so I'm not sure what text you put in between the numbers, but you can write that as a loop as well, with an if statement to tack on the separator for every number other than the first one.


==========================
That reduces the program written above, to:

void LuckyDip1_actionPerformed(Acti... e) {
int[] array = new int [6];

for (int i=0; i array[i] = 1 + (int)(Math.random()*49);

java.util.Arrays.sort(array);

String txt = "";
for (int i=0; i if (i > 0) txt += ", ";
txt += array[i];
}

jTextField1.setText(txt);

=====================
You could also refactor the creation of the random number into a separate method, but it is only one line of code and it is not repeated when implemented as a loop, so there's not much gain there.

The implementation would get a little more complex if you wanted your numbers to contain no repeats. Right now, there's nothing preventing two of your six numbers from being the same.

2007-07-26 03:34:19 · answer #1 · answered by McFate 7 · 0 0

fedest.com, questions and answers