I have the following code to generate an array of random numbers. How can I get it to print the array like [5,89,76,34,2] instead of printing down. I don't think it is actually printing the array just the numbers.

import java.util.Random;

public class RandomIntArray 
{
	private int[] numbers;
	
	public RandomIntArray(int size)
	{       
		numbers = new int[5]; 
	}

	public static void main(String[] args) 
	{
		 int[] numbers = new int[5];
		  Random generator = new Random();
		  for (int i = 0; i < numbers.length; i++)
		  {

			  int n = generator.nextInt(100);
			  numbers[i] = n;
		  } 
		
		for (int i = 0; i < numbers.length; i++) {
			  System.out.println(numbers[i]);
			}

	}

}

If you want to print something without adding a new line at the end, use System.out.print() instead (notice it is print, not println). Also, you could add a comma or white space as many as you want in the print. That's your decision of formatting the print out.

Wow, thank you I didn't even notice that...it's been a long night.

I added the method to get sum

public int sum()
	{
	    int total = 0;
        for(int element : numbers)
        {
            total = total + element;
        }
        return total;
	}

how would I print this in the main method?

If a method return a value that can be display out to the console directly (primitive type but not array), you could simply call System.out.print or System.out.println as well.

System.out.println("Sum is "+sum());

PS: The code line above does NOT store the sum value returned by the sum() method but directly uses it to display on the console.

That's how I thought I would do it but when I place the line in my code it says that I cannot make a static reference to a non-static method.

Oh I forgot... You declare sum() method in the RandomIntArray class. But then your main() method is using all local variable. As a result, the sum() cannot be used with main() method which is a static method.

There are a couple ways to fix this. However, I don't know how much you are into Java now. First way of fixing this is to really implement the class and use it in your main() method.

class RandomIntArray {
  int[] numbers;
  // create constructor for the class
  public RandomIntArray {
    numbers = new int[5];
  }
  ...
  ...
  public int sum() {
    ...
  }

  public static void main(String args[]) {
    Random generator = new Random();
    RandomIntArray myArr = new RandomIntArray();  // create & initiate the class object
    for (int i = 0; i < myArr.numbers.length; i++) {
      int n = generator.nextInt(100);
      myArr.numbers[i] = n;
    } 

    for (int i = 0; i < myArr.numbers.length; i++) {
      System.out.println(myArr.numbers[i]);
    }

    // now you can call sum()
    System.out.println("Sum is "+myArray.sum());
  }  // end main()
}

Second way is to make the sum() method static. But doing so, you need to pass in your "numbers" variable.

class RandomIntArray {
  ...
  public static int sum (int[] numbers) {
    ...
  }

  public static void main (String[] args) {
    ...
    ...
    // You may call sum(numbers) if it is being used in its own class main() method.
    // But you must call it this way if you are going to use it somewhere else.
    System.out.println("Sum is "+RandomIntArray.sum(numbers));
  }
}

PS: Please read more about Java "static" method for further information.

I implemented the first idea but now it is telling me that the constructor is undefined and that myArray cannot be resolved.

Oops, the constructor line should be public RandomIntArray()... Sorry >_<

Is there a way to do it with the constructor taking the size parameter. The constructor was given to us in the assignment instructions so I don't want to change it. I know in past labs I've done something along the lines of

public RandonIntArry(int size)
{       
numbers = new int[5];
s = size;
}

and then in the main method

RandomIntArray myArr = new RandomIntArray(s);

but cannot get this to work like it has in the past.

You could by adding another constructor. However, you should also define default values for the size in the default constructor.

...
  int size;

  // constructor 1 (default constructor)
  public RandomIntArray() {
    size = 5;
    numbers = new int[size];
  }
  // constructor 2
  public RandomIntArray(int s) {
    if (s>0) {
      size = s;
      numbers = new int[size];
    }
    else {
      // do whatever you want here (could define default value or reject)
    }
  }
  ...

I started implementing the above and read the assignment again...the program is supposed to have a single constructor. It says:
It should have a single constructor that takes 1 parameter-an int that indicates the size of the array it should create. The constructor should create an appropriate seized array and populate the array with Random numbers in the range 100 to 199. Use the java.util.Random method to generate the random numbers in a loop.
'
Do you think this means I should have my generator in the constructor? Is this even possible?

Do you think this means I should have my generator in the constructor? Is this even possible?

Yes to both.

So would the correct way be to do something like this:

import java.util.Random;

public class RandomIntArray 
{
	private int[] numbers;
	
	public RandomIntArray(int size)
	{       
		numbers = new int[5];

		Random generator = new Random();
		
		for (int i = 0; i < numbers.length; i++) 
		{
			int n = generator.nextInt(100);
			numbers[i] = n;
		}
	public int sum()
    {
        int total = 0;
        for(int element : numbers)
        {
            total = total + element;
        }
        return total;
    }
	
	public static void main(String args[]) 
	{

		for (int i = 0; i < numbers.length; i++) 
		{
			System.out.println(numbers[i]);
		}
	}

You're OK untill you get to main.
In main you need to create an instance of your class (passing a suitable size into the constructor). Then you can use that instance to call sum(). Rather than have that print loop in main trying to access the private int array (which won't work because the array is, quite rightly, not static), why not put that code into a print() method that you can also call from main?

Are you saying something along these lines?

import java.util.Random;

public class RandomIntArray 
{
	private int[] numbers;
	
	public RandomIntArray(int size)
	{       
		numbers = new int[5];

		Random generator = new Random();
		
		for (int i = 0; i < numbers.length; i++) 
		{
			int n = generator.nextInt(100);
			numbers[i] = n;
		}
	public int sum()
    {
        int total = 0;
        for(int element : numbers)
        {
            total = total + element;
        }
        return total;
    }
	
	public static void main(String args[]) 
	{
		System.out.println(total.sum());
	}
		private int total;
	}

No, not really. Let's go back to my previous post...

In main you need to create an instance of your class (passing a suitable size into the constructor).

We create new instances of a class by using the "new" keyword, eg to create an instance of a class RandomIntArray with a given size, eg 10, and keep a reference to it you write something like:

RandomIntArray myRIA = new RandomIntArray (10);

Then you can use that instance to call sum().

That's just an ordinary method call, as in

System.out.println(myRIA.sum());

ps you are still missing a } at the end of one of your methods.

I hope this is my last question...I have implemented an average method which is working almost perfect however I get a new array instead of it using the original array and it's not rounding correctly.

import java.util.Random;

public class RandomIntArray 
{
	private int[] numbers;
	
	public RandomIntArray(int size)
	{       
		numbers = new int[5];

		Random generator = new Random();
		
		for (int i = 0; i < numbers.length; i++) 
		{
			int n = generator.nextInt(100);
			numbers[i] = n;
		}
		for (int i = 0; i < numbers.length; i++)
		{
		System.out.print(numbers[i]+ " ");
		}
	}
	public int sum()
    {
        int total = 0;
        for(int element : numbers)
        {
            total = total + element;
        }
        return total;
    }
	
	public double average()
	{
		RandomIntArray numArray = new RandomIntArray (5);
		double average = numArray.sum() / numbers.length;
		return average;
	}
	public static void main(String args[]) 
	{
		
	      RandomIntArray numArray = new RandomIntArray (5);
	      System.out.println("\n" + numArray.sum());
	      System.out.println(numArray.average());
	}
	}

Why create a new array on line 35? You have to work with the existing array numbers. This is a mistake.
Were you worried by the call on line 36 numArray.sum() ?
Because you are in the average method Java already knows what object you are using, so you can just call sum() to get the sum of the current array.

Oh I see...the first time I tried it without creating the new array I put in myArray.sum() and it was an error but all I needed to put in was sum() and it worked correctly. There is obviously a rounding error in the average method as well but I'm not sure how to fix it. Is using the type double correct?

double looks OK to me. No idea why you have a rounding error.
ps - going offline now till tomorrow

I think the error said about loss of precision? Update line 36 to...

double average = (double) numArray.sum() / numbers.length;

That fixed the problem there...now I'm trying to create a method to find the max and min. The max method is working correctly but no matter how I write the min method it keeps returning zero even when zero isn't a part of the array.

public int max()
	{
		int max = 0;
		for(int element : numbers)
		{
			if(element > max) 
			{
				max = element;
			}
		}


		return max;
	}
	
	public int min()
	{
		int min = 0;
		for(int element : numbers)
		{
			if(element > 0 && element < min) 
			{
				min = element;
			}
		}


		return min;
		
	}

I guess your number must be positive integer? Because you initial min to the lowest number possible, any element value will never be greater than the initial min value. As a result, the "if" statement is always determined as false. What you can do is to initial the min value to possible maximum integer value.

int min = Integer.MAX_VALUE;

If I wanted to find if a number is in the array is this along the lines of what I should be doing? I know it's not correct but am I going in the right direction?

public int search(int ix)
	{
		for(numArray : numbers)
		{
			if(numArray.RandomIntArray() == ix)
				return numArray;
		}
		return null;
		}

The caller already knows what the value of the element it is searching, so returning the element value is useless. If you are returning an integer, you should return the index value found in the array. In this case, the value return greater than or equal to 0 are found; otherwise returns a negative value (often time is -1).

You must not (and cannot?) return "null" when you are returning primitive integer. Please fix the idea of what you are returning to the caller - the index found in the array instead of the value of the number itself. Also, you need to use a simple for-loop instead of this iterator.

Now the last question...I want to use JOptionPane with this...it is prompting me to get the array size but will not give me any input

import java.util.Scanner;
import javax.swing.JOptionPane;

public class RandomIntArrayDriver
{
	
 public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        String input = JOptionPane.showInputDialog("Enter the size of the array: ");
        int size = in.nextInt();
       
          RandomIntArray numArray = new RandomIntArray (size);
          JOptionPane.showMessageDialog("\n" + "Sum: " + numArray.sum());
          System.out.println("Average: " + numArray.average());
          System.out.println("Max: " + numArray.max());
          System.out.println("Min: " + numArray.min());
          System.out.println("Size: " + numArray.getSize());
          System.out.println("Numbers: " + numArray.toString());
         
    }
}

The value coming in from the "input" is a string. If the input value is guarantee as an integer, you could simply do

int size = Integer.parseInt(input);

Unfortunately, the input is often invalid from a user. You will need to validate the input string before you can really use it. You may need a while loop to do that for you, and use InputMismatchException to keep the loop alive if the input is invalid.

So I would replace int size = in.nextInt() with int size = Integer.parseInt(input);?

The value coming in from the user is guaranteed to be an integer we do not have to test for invalid input so if I make this change would I be able to use JOptionPane.showMessageDialog?

Yes, replace that line. Also, remove the Scanner declaration because you won't need it.

The showMessageDialog() method is to display a message and you should be able to.

JOptionPane.showMessageDialog(null, "A display message");

Yep that worked...I really thought that was my last question because I thought that the toString method would work the same in an ArrayList but it doesn't...I have to convert the entire program to ArrayList and everything works but this...

public String toString()
    {
    	return this.RandomIntArrayList(int);
    }

I have looked in and out of my book and thought about changing the ArrayList to an array and then toString but cannot figure out how.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.