1

I have been stuck for about an hour and after googling and doing research I could't get my code to run. It shows not a single error and when I press run it just opens debug and does nothing. I am using eclipse. I am trying to create a list of 10 objects and to give them random numbers.

class test {
public static void main(String[] args){
 int a [] = new int[9];{
 for (int i = 0; i < a.length; i++)
 a[i] = a[(int)(Math.random()*70+15)];
 for (int elem : a){
 System.out.println(elem);
 }; 
}}}
asked Mar 19, 2013 at 16:11
1
  • 1
    indenting, and not having random curly-brace blocks make code easier to read Commented Mar 19, 2013 at 16:18

3 Answers 3

6

If you are actually launching the application, it should fail with an exception at the following line:

 a[i] = a[(int)(Math.random()*70+15)];

Here, a[] consists of nine elements, so its highest index is 8. However, Math.random()*70+15 is guaranteed to generate numbers that are greater than 8.

answered Mar 19, 2013 at 16:13
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah I was about to say... If he didn't get an error there, then he rolled rather low
Sorry I just tried to give one elemnt value and it didnt work I changed it.
@Cruncher: He couldn't have. The +15 makes this fail every single time.
@NPE: yeah I realised after I posed
it might be worthwhile to edit the failing code excript to reflect the op's updated code. just so that nobody is confused.
2

I don't know any Java, but I would say :

for (int i = 0; i < a.length; i++)
a[2] = a[(int)(Math.random()*70+15)];

should be

for (int i = 0; i < a.length; i++)
a[i] = (int)(Math.random()*70+15);
answered Mar 19, 2013 at 16:14

Comments

1

I would suggest using the Random number generator instead. I would also suggest using better names than i or a for your programs.

import java.util.Random;
class test {
 public static void main(String[] args){
 Random object = new Random ();//declare for your object
 int a; //declare your integer type (I would suggest 
 // changing that to be more descriptive)
 for (int i = 1; i <=10; i++) 
 {
 a = object.nextInt(100); // change 100 to however large 
 // parameter you want
 System.out.println(a + " ");
 }
 } 
}
lrnzcig
3,9474 gold badges40 silver badges53 bronze badges
answered Dec 17, 2016 at 19:46

1 Comment

For java7 and above it is best to use ThreadLocalRandom. Take a look e.g. here

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.