-3

I have to use the math.random to populate my array with 25 random integers between the range 10 and 99. I'm also having problems trying to print the array. Instead of the full array being printed, only the memory location is printed. How to I write the command for it to print? This is how I've written my code and I know there's something wrong with it but just done know how to iron it out.

  public class Proj5COMP110
{
public static void main(String args[])
 {
System.out.println ("Project 5: Quick Sort");
    int i;
    int mSample [] = new int[25];
    for ( i= 0; i< mSample.length ; i++) 
    {
        mSample[25] = (int)(Math.random ()* (99-10)+10);
    }
System.out.print(mSample[25]);
 }
}
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
RexUmbra
  • 1
  • 1

3 Answers3

0

You are storing values into wrong index. use mSample[i] instead of mSample[25] to store value at index i.

 mSample[i] = (int)(Math.random ()* (99-10)+10);

Also don't forget to change this line: System.out.print(mSample[25]); This will give you an indexOutOfBounds exception. Learn why this exception occurred.

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
0
    public class Proj5COMP110
{
public static void main(String args[])
 {
System.out.println ("Project 5: Quick Sort");
    int i;
    int mSample [] = new int[25];
    for ( i= 0; i< mSample.length ; i++) 
    {
        mSample[i] = (int)(Math.random ()* (99-10)+10);
    }
for ( i= 0; i< mSample.length ; i++) 
    {
        System.out.print(mSample[i]);
    }

 }
}

In an array the index starts from 0, therefore you should be able to store from mSample[1-24], mSample[25] would be out of bounds. When you are trying to print mSample[25], it is printing garbage value and not memory address.

Devanshi Mishra
  • 487
  • 5
  • 15
0
  1. The problem as already mentioned in comments is that you have to change
mSample[25] = (int)(Math.random ()* (99-10)+10); 

to

mSample[i] = (int)(Math.random ()* (99-10)+10);
  1. I would like to prefer below code, which is less erroneous and doesn't have any warning.
  public static void main(String[] args) {
    int[] mSample = new int[25];
    for (int loop = 0; loop < mSample.length; loop++)
        mSample[loop] = new Random().nextInt(90) + 10;
    for (int element : mSample)
        System.out.println(element);
  }
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31