I'm building a class that takes an array of numbers and has methods to output their min, max and average values as a string representation of the numbers. Here's my constructor for the class:
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
I'm getting the array out of bounds exception message when I test this class with a driver program and this constructor is the one causing it. I'm not able to understand how I'm going beyond the size of the array here. Please help! Thanks.
Edit - So just to clear up any confusion I'm posting the entire class below for reference:
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers = new int[size];
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
public int min_value()
{
for (int i = 0;i < size - 1;i++)
{
min = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] < min)
{
min = numbers[k];
}
else
{
min = numbers[i];
}
}
}
return min;
}
public int max_value()
{
for (int i = 0;i < size - 1;i++)
{
max = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] > max)
{
max = numbers[k];
}
else
{
max = numbers[i];
}
}
}
return max;
}
public double average()
{
double avg;
int sum = 0;
for (int i = 0;i < size;i++)
{
sum = sum + numbers[i];
}
avg = sum/size;
return avg;
}
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = Integer.toString(numbers[i]) + " ";
}
return array;
}
}
You are initializing the array before you initialize the size variable. The size variable has a default value which is passed into the array constructor and sets the array to that size. to fix the problem just move the initialization of the array into the constructor after the size variable is set.
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers;
public RandomArray(int sizeOfArray) {
Random generator = new Random();
size = sizeOfArray;
numbers = new int[size];
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
Also I've noticed a bug with the string output method. The array would be overwritten on each iteration. To solve this you must add the array to itself.
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = array + Integer.toString(numbers[i]) + " ";
}
return array;
}
Your method is passed the size of the array, but the array definition is not present in your code.
If you need to create the array in the RandomArray method, do something like :
public int[] RandomArray(int sizeOfArray)/*Constructor: gets array size, create and populates array with random numbers*/
{
int[] randomArray = new int[sizeOfArray];
for (int i = 0;i < randomArray.length();i++)
{
numbers[i] = generator.nextInt(size + 1);
}
return randomArray;
}
As you did not provide the entire class code it is hard to see whats going on. However I think you did not initialize the array correctly. If you have a private variable for an array, you should still 'make space' for it, as follows.
private int[] myIntArray; // As class member
myIntArray = new int[3]; // To allocate memory for the array
See the following link, for more info regarding arrays.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Related
I have a problem to convert from int to int []. I have tried to modify the coding but still have error. I want to change the method getRandomNumberInRange into int[] because i need to combine with [hostType] and [hostType] is in array form.
// this method is to convert from int to int[]
static Integer[] toObject(int[] intArray) {
Integer[] result = new Integer[intArray.length];
for (int i = 0; i < intArray.length; i++) {
result[i] = Integer.valueOf(intArray[i]);
}
return result;
}
// this method to generate random number
public static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
//this method is to implement the function getRandomNumberInRange and need to be in array form
public static List<PowerHost> createHostList(int hostsNumber) {
List<PowerHost> hostList = new ArrayList<PowerHost>();
for (int i = 0; i < hostsNumber; i++) {
int hostType = i % Constants.HOST_TYPES;
// int mips2[]=(int) getRandomNumberInRange(100, 1000);
List<Pe> peList = new ArrayList<Pe>();
for (int j = 0; j < Constants.HOST_PES[hostType]; j++) {
int[] obj = new int[hostType] ;
Integer[] newObj = toObject(obj);
peList.add(new Pe(j, new PeProvisionerSimple(getRandomNumberInRange(100, 1000)[newObj])));
}
There are a few things wrong. First, in the last code snippet, you are missing two '}'s. Second, getRandomNumberInRange(int min, int max) returns an int, which is not an array. What that means is that you wouldn't do getRandomNumberInRange(100, 1000)[newObj] because that is like doing 107[4]. 107 isn't an array so that wouldn't work. Also, newObj is an array, so even if getRandomNumberInRange returned an array, newObj wouldn't be able to be used as an index to get the int in the array. This is because the index (the thing that goes in array[here]) must be an int.
Beginner in Java. I'm stuck trying to figure out how to write one of the constructors for a java project. I'm going to include most of the code to provide some context. This class is to be accessed by another file which holds the methods for a terminal menu.
// java class for keyboard I/O
import java.util.Scanner;
// declaration of the class
public class NumberList
{
//integer constant that determines the size of the array
public static final int MAX_CAPACITY = 100;
//array to store the numbers
private double [] numbers;
//the number of valid numbers currently in the NumberList
private int length;
//default constructor that initializes array to size MAX_CAPACITY and initializes all
//array values to 0, sets length to 10
public NumberList()
{
numbers = new double[MAX_CAPACITY];
int i;
for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = 0;
length = 10;
}
//outputs the numbers in the NumberList to the
//standard output screen
public void print()
{
int i;
for(i = 0; i < length-1; i++)
System.out.println(numbers[i]+ ", ");
System.out.println(numbers[i]);
}
//assignment constructor, initializes array to size 100,
//initializes length to l and sets the first l values of the list to the value n
NumberList(int l, double n)
{
numbers = new double[MAX_CAPACITY];
length = l;
int i;
for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = n;
}
//array constructor, initializes array to size 100, takes an array
//as input and completes a deep copy (element to element copy) from the array
//parameter to the numbers array
NumberList(final double[] a)
{
this.numbers = new double[a.length];
for (int i = 0; i < a.length; ++i)
{
this.numbers[i] = a[i];
}
}
Everything above compiles nicely. Not sure if I'm on the right track or if a "for" loop is necessary.
**//copy constructor, initializes array to size 100,
//creates a copy of parameter NumberList nl to the calling NumberList
NumberList(final NumberList nl)
{
numbers = new double[MAX_CAPACITY];
nl = new NumberList(MAX_CAPACITY);
}**
//returns the length of NumberList
public int length()
{
int length = numbers.length;
return length;
}
//returns the sum of the numbers in the NumberList
public double sum()
{
double sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum = sum + numbers[i];
}
return sum;
}
Grateful for any tips/ advice I can get.
A copy constructor is just that: A constructor. So you're operating on a new instance freshly created for you. You don't want to create another instance, just set up this.
For instance, in your case, make the numbers of the current instance a copy of the numbers of the source instance, and copy length:
NumberList(final NumberList nl)
{
this.numbers = nl.numbers.clone();
this.length = nl.length;
}
(With thanks to Jorn Vernee and assylias for pointing out Arrays.copyOf and clone, respectively. Went with clone.)
Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.
//Main
public class Lab_4_Practice {
public static void main(String[] args) {
//Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = (total / randomArray.length);
//Call Methods
random(randomArray);
displayRandom(randomArray);
largest(maxIndex, randomArray);
smallest(minIndex, randomArray);
sum(total, randomArray);
average(total, randomArray);
sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
//***************************************************
//Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
randomArray[i] = (int)(Math.random() * 300);
}
}
//Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
//Method identifies largest index and its element in array
public static void largest(int maxIndex, int[] randomArray) {
for (int l = 1; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
}
//Method identifies smallest index and its element in array
public static void smallest(int minIndex, int[] randomArray) {
for (int i = 1; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
}
//Method calculates sum of elements
public static int sum(int total, int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
total = total + randomArray[i];
}
return total;
}
//Method calculates average of elements
public static void average(int total, int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
i += randomArray[i];
}
}
//Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
//Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
//Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
}
Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -
public class Example{
public void assign(int[] Array){
for(int i=0;i<Array.length;i++){
Array[i]=(int)(Math.random()*300);
}
}
public void display(int[] Array){
System.out.println("The 10 elements of the array are:");
for(int i=0;i<Array.length;i++){
System.out.println(Array[i]);
}
}
public int sum(int[] Array) {
int total =0;
for(int i=0;i<Array.length;i++){
total=total+Array[i];
}
return total;
}
//write all other methods here in this class.
}
now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -
public static void main(String[] args) {
int[] randomArray=new int[10];
Example e=new Example();
e.assign(randomArray);//this must be called first to assign the values inside the array.
e.display(randomArray);//call this method if you wish to display the values.
System.out.println("The sum of the elements are: "+e.sum(randomArray));
}
I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.
public class StackProblem {
public static void main(String[] args) {
// Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = 0;
// Call Methods
random(randomArray);
displayRandom(randomArray);
sortArray(randomArray);
maxIndex=largest(randomArray);
minIndex=smallest(randomArray);
total=sum(randomArray);
average=average(total, randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 300);
}
}
// Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
int maxIndex=0;
for (int l = 0; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
int minIndex=0;
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Method calculates sum of elements
public static int sum(int[] randomArray) {
int localTotal=0;
for (int i = 0; i < randomArray.length; i++) {
localTotal+=randomArray[i];
}
return localTotal;
}
// Method calculates average of elements
public static int average(int total, int[] randomArray) {
return total/randomArray.length;
}
// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]
This is the typical pattern for a method calculating some value from the elements of an array:
public static int largest(int[] array) {
int maxIndex = 0;
for (int l = 1; l < array.length; l++) {
if (array[l] > array[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
And you call it like this:
int maxIndex = largest( randomArray );
Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.
If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.
Finally, the code for calculating the average is very much in error.
public static double average( int[] array ) {
return (double)sum( array )/array.length;
}
and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)
The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:
randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.
Working on building an array that can generate random integer values inside an array. It prints the random numbers but it prints it like this
[10][2][5][7][6][2][4][7][2][10][0]--->(down the side)--------> and want it to print like this [10,7,5,9,4,3,4,7,2,3] (one line).
public class ArrayLab
{
//array instance variable
private int[] array1 = new int[10];
//array constructor
public ArrayLab(int integer)
{
//class parameter = 10
int[] array1 = new int[]{integer};
}
public void initialize()
{
//allow randomization of numbers inside the array field.
System.out.println(Arrays.toString(array1));
//prints [0,0,0,0,0,0,0,0,0,0] which is ok
System.out.println();
for (int iteration = 0; iteration < array1.length; iteration ++)
{
Random number = new Random();
number.nextInt(10);
int n = number.nextInt(11);
int[] array1 = new int[]{n};
System.out.println(Arrays.toString(array1));
//prints down the side. Want on one line?
}
}
}
Just change
System.out.println(Arrays.toString(array1));
//new output
System.out.print(Arrays.toString(array1));
another way you can get this done is by using a for loop to iterate through the array in similar fashion
for( int i = 0; i < array1.length; i++ ){
System.out.print(array1[i]+" ");
}
for the random numbers
Random ran = new Random();
for( int i = 0; i < array1.length; i++ ){
int number = ran.nextInt((max - min) + 1) + min;
//insert the maximum and min values for your generator
array1[i] = number;
So I created an array with random numbers, i printed and counted the repeated numbers, now I just have to create a new array with the same numbers from the first array but without any repetitions. Can't use ArrayList by the way.
What I have is.
public static void main(String[] args) {
Random generator = new Random();
int aR[]= new int[20];
for(int i=0;i<aR.length;i++){
int number=generator.nextInt(51);
aR[i]=number;
System.out.print(aR[i]+" ");
}
System.out.println();
System.out.println();
int countRep=0;
for(int i=0;i<aR.length;i++){
for(int j=i+1;j<aR.length-1;j++){
if(aR[i]==aR[j]){
countRep++;
System.out.println(aR[i]+" "+aR[j]);
break;
}
}
}
System.out.println();
System.out.println("Repeated numbers: "+countRep);
int newaR[]= new int[aR.length - countRep];
}
Can someone help?
EDIT: Can't really use HashSet either. Also the new array needs to have the correct size.
Using Java 8 and streams you can do the following:
int[] array = new int[1024];
//fill array
int[] arrayWithoutDuplicates = Arrays.stream(array)
.distinct()
.toArray();
This will:
Turn your int[] into an IntStream.
Filter out all duplicates, so retaining distinct elements.
Save it in a new array of type int[].
Try:
Set<Integer> insertedNumbers = new HashSet<>(newaR.length);
int index = 0;
for(int i = 0 ; i < aR.length ; ++i) {
if(!insertedNumbers.contains(aR[i])) {
newaR[index++] = aR[i];
}
insertedNumbers.add(aR[i]);
}
One possible approach is to walk through the array, and for each value, compute the index at which it again occurs in the array (which is -1 if the number does not occur again). The number of values which do not occur again is the number of unique values. Then collect all values from the array for which the corresponding index is -1.
import java.util.Arrays;
import java.util.Random;
public class UniqueIntTest
{
public static void main(String[] args)
{
int array[] = createRandomArray(20, 0, 51);
System.out.println("Array " + Arrays.toString(array));
int result[] = computeUnique(array);
System.out.println("Result " + Arrays.toString(result));
}
private static int[] createRandomArray(int size, int min, int max)
{
Random random = new Random(1);
int array[] = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = min + random.nextInt(max - min);
}
return array;
}
private static int[] computeUnique(int array[])
{
int indices[] = new int[array.length];
int unique = computeIndices(array, indices);
int result[] = new int[unique];
int index = 0;
for (int i = 0; i < array.length; i++)
{
if (indices[i] == -1)
{
result[index] = array[i];
index++;
}
}
return result;
}
private static int computeIndices(int array[], int indices[])
{
int unique = 0;
for (int i = 0; i < array.length; i++)
{
int value = array[i];
int index = indexOf(array, value, i + 1);
if (index == -1)
{
unique++;
}
indices[i] = index;
}
return unique;
}
private static int indexOf(int array[], int value, int offset)
{
for (int i = offset; i < array.length; i++)
{
if (array[i] == value)
{
return i;
}
}
return -1;
}
}
This sounds like a homework question, and if it is, the technique that you should pick up on is to sort the array first.
Once the array is sorted, duplicate entries will be adjacent to each other, so they are trivial to find:
int[] numbers = //obtain this however you normally would
java.util.Arrays.sort(numbers);
//find out how big the array is
int sizeWithoutDuplicates = 1; //there will be at least one entry
int lastValue = numbers[0];
//a number in the array is unique (or a first duplicate)
//if it's not equal to the number before it
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
sizeWithoutDuplicates++;
}
}
//now we know how many results we have, and we can allocate the result array
int[] result = new int[sizeWithoutDuplicates];
//fill the result array
int positionInResult = 1; //there will be at least one entry
result[0] = numbers[0];
lastValue = numbers[0];
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
result[positionInResult] = i;
positionInResult++;
}
}
//result contains the unique numbers
Not being able to use a list means that we have to figure out how big the array is going to be in a separate pass — if we could use an ArrayList to collect the results we would have only needed a single loop through the array of numbers.
This approach is faster (O(n log n) vs O (n^2)) than a doubly-nested loop through the array to find duplicates. Using a HashSet would be faster still, at O(n).