Re: bit of help please...
Quote:
Originally Posted by
Andrew123
i am very new to java programming and it will be evident in the code i have written, however, i have watched a few tutorials and i am trying to put together a few parts of java i have learnt and i have thought about how to write this for so long but i just cannot do this :( basically heres my code, and you may be able to tell what i am trying to do with it, if not, i will explain after anyway:
import java.util.Random;
public class array {
public static void main(String[] args){
Random rndmNum = new Random();
int numArray[] = new int[10];
int Number;
for(int counter=0;counter<10;counter++){
Number= numArray[1 + rndmNo.nextInt(99)];
System.out.println(counter + "=" + Number);
}
}
}
i was hoping this programme would do something close to reading in an array of size 10 int, making 10 random integers, and the bit i was finding the hardest: allocating these random numbers into the array, and then printing the number of the array out and the random value it has taken, the random value being between 1-100. please can someone help me clear this up i am sure there are a lot of errors and i have probably forgotten a few lines of essential code to make this work, thanks guys.
hallo, your array is declared with int[10] so the range for the index is from 0 to 9. now, the expression numArray[1 + rndmNo.nextInt(99)] generate an index between 1 and 100, which cause an IndexOutOfException. i think your code should look like
Code :
import java.util.Random;
public class array {
public static void main(String[] args) {
Random rndmNum = new Random();
int numArray[] = new int[10];
int Number;
for (int counter = 0; counter < 10; counter++) {
// generate a number in range 1..100
Number = rndmNum.nextInt(100) + 1;
numArray[counter] = Number;
System.out.println(counter + "=" + Number);
}
}
}
an improvement to the code is to check if the generated number is already in your list. so generate a number, until the check become false.
Re: bit of help please...
thank you very much!
i thought i was missing something, and i was also getting mixed up between having the ten random numbers and what ranged those ten random numbers could be in.
i will practice a few more like this from scratch, maybe using more than one method.
once again, thank you very much i had been kicking myself over this, and i thought i could do it as a couple of years ago i learnt c++ and a programme like this was no problem then :)