ArrayList and java.lang.OutOfMemoryError - java

I am trying to make program that create an ArrayList of initial size of 1 and populate it with random numbers. Next, the ArrayList is cleared and the size of ArrayList is increased by 1 and again filled with random numbers. I want my program to repeat those steps until the ArrayList size will be equal to number specified by user.
So the output will be for example like:
1
3,8
6,3,7
...
n
I have produced so far:
public static void main (String args[]){
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =1;
while(val<400){
for (int j = 0; j<ii;)
{
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Any ideas how to make it work?

You never increment j.
You are incrementing ii and val inside the for loop where as I think you actually want to do it in the while loop. Try the example below.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =0;
while(val < 400){
for (int j = 0; j<ii; j++) {
int pick = rand.nextInt(100);
al.add(pick);
}
ii++;
val++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Your task would be much easier if you gave your variables meaningful names. e.g.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int lineNumber = 1;
int lineLength = 0;
while(lineNumber < 400){
for (int randCount = 0; randCount < lineLength; randCount++) {
int pick = rand.nextInt(100);
al.add(pick);
}
lineLength++;
lineNumber++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}

for (int j = 0; j<ii;) {
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
is an infinite loop(j is always 0 and ii is always positive). You should fix it(according to the desired semantics).

Related

How to print a histogram from the values in an array in reverse order with nested for loops

I have assignment where I have to print and fill an array consisting of 50 indices with random integers then print the values out. Then below that print a list of the numbers in the reverse index with a histogram next to each value. Im supposed to use a nested for loop to solve this and only could get the first section of the problem so far. This is my first time using stackoverflow and I am not expecting an upright answer but if someone could help me understand nested for loops a little more, it would be greatly appreciated.
public static void main(String[] args) {
Random ranGen = new Random();
int[] ranArray = new int [SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for(int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
for(int j = 0; j < ranArray[i]; j++) {
System.out.println("Histrogram");
System.out.println(ranArray[i] );
}
}
}
}
How the output of the code should look like
For the second section, you can iterate on each random number again and for each number, print it with System.out.printf("%-5d", number) ("%-5d" pads the number with spaces to the right) and have a nested loop from 0 to number-1 and print the start with System.out.print(stars).
public static void main(String[] args) {
int SIZE = 5;
Random ranGen = new Random();
int[] ranArray = new int[SIZE];
char stars = '*';
System.out.println("Array: " + "\n");
for (int i = 0; i < ranArray.length; i++) {
int rangeLimit = ranGen.nextInt((45 - 5) + 1) + 5;
ranArray[i] = ranGen.nextInt(rangeLimit);
System.out.println(ranArray[i]);
}
System.out.println("-------------------------");
System.out.println("Histograms:");
for (int i = ranArray.length - 1; i >= 0; i--) {
System.out.printf("%-5d", ranArray[i]);
for (int j=0; j<ranArray[i]; j++) {
System.out.print(stars);
}
System.out.println();
}
}

How can I sum these two arrays into a new one?

How can I sum these two arrays into a new one? Where the first value of the arrayA sums the first value of the arrayB?
public class Exercises {
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
static PrintStream out = System.out;
public static void main(String[] args) throws IOException {
int numbersA[] = new int[5];
int numbersB[] = new int[5];
int numbersC[] = new int[5];
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int j = 0;
for (int i = 0; i < 5; i++) {
numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
}
{
out.print("The sum of the two arrays are: " + numbersC[j] + " ");
}
out.println();
}
}
You were pretty close. numbersA[i] and numbersB[i] (not the length of each array). Also, you don't need j and should print the prelude before the loop. Like,
out.print("The sum of the two arrays are: ");
for (int i = 0; i < 5; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
Finally, your code relies on magic numbers (hard coded array lengths). That is bad practice, instead you should use the array.length so your code doesn't require changing when your array sizes change. Like,
int[] numbersA = new int[5];
int[] numbersB = new int[5];
for (int i = 0; i < numbersA.length; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < numbersB.length; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int[] numbersC = new int[Math.min(numbersA.length, numbersB.length)];
out.print("The sum of the two arrays are: ");
for (int i = 0; i < numbersC.length; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
try to delete the numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
length from both
use this shape
numbersC[i] = numbersA[i] + numbersB[i];
i think it will be work now

java if statement in array for loop

Alright so I need to add some additional functions to this array, which gives 10 random integers. It needs to be able to store the numbers that are less than 40 and print them along with the numbers that are less than the average. How do I do this with an if statement in a for loop? (Ignore the stuff that's cometted out.
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
for(int i=0; i<ages.length; i++){ //adds stuff to arrays
ages[i] = gen.nextInt(100); //Determines the maximum used in random number generation
}
for(int x=0; x<10; x++){//prints the array with the below statement
System.out.println(ages[x]);
}
System.out.println("---------------");
System.out.println(ages[9]);
System.out.println(ages[8]);
System.out.println(ages[7]);
System.out.println(ages[6]);
System.out.println(ages[5]);
System.out.println(ages[4]);
System.out.println(ages[3]);
System.out.println(ages[2]);
System.out.println(ages[1]);
System.out.println(ages[0]);
int value = (ages[0] + ages[1] + ages[2] + ages[3] + ages[4] + ages[5] + ages[6] + ages[7] + ages[8] + ages[9]);
System.out.println("The combined value of the integers is " + value + ".");
int average = (value / 10);
System.out.println("The average value of the integers is " + average + ".");
}
}
Something like that? (Sorry guys for code but i don't have a time to make it better):
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
List<Integer> agesLesserThan40 = new ArrayList();
List<Integer> agesLesserThanAverage = new ArrayList();
float value = 0;
for(int i=0; i<10; i++) {
ages[i] = gen.nextInt(100);
value += ages[i];
}
for(int x=0; x<10; x++){
if(ages[x] < value/10) agesLesserThanAverage.add(ages[x]);
if(ages[x] < 40) agesLesserThan40.add(ages[x]);
}
System.out.println("ages:");
for(int z=0; z<10; z++){System.out.print(ages[z] + ", ");}
System.out.println();
System.out.println("Lesser than 40: ");
for(int y=0; y<agesLesserThan40.size()-1; y++){System.out.print(agesLesserThan40.get(y) + ", ");}
System.out.println();
System.out.println("Lesser than average: ");
for(int y=0; y<agesLesserThanAverage.size()-1; y++){System.out.print(agesLesserThanAverage.get(y) + ", ");}
System.out.println();
System.out.println("The average value of the integers is " + value / 10 + ".");
System.out.println("The combined value of the integers is " + value + ".");
}
}
I have no idea how if (value >= 100000) says anything is less than 40...
Here is probably how you could divide your array into above and under 40.
final int AGES_TO_GENERATE = 10;
final int AGE_LIMIT = 100;
final int AGE_DIVIDER = 40;
List<Integer> lesserAge = new ArrayList<>();
List<Integer> upperAge = new ArrayList<>();
Random gen = new Random();
double averageAge = 0.0;
for(int i=0; i<AGES_TO_GENERATE; i++){
int age = gen.nextInt(AGE_LIMIT);
averageAge += age;
if (age < AGE_DIVIDER) lesserAge.add(age);
else upperAge.add(age);
}
averageAge /= AGES_TO_GENERATE;
System.out.println("Here are the values less than 40");
System.out.println(lesserAge);
if (upperAge.isEmpty()) {
System.out.println("There are no values over 40");
}
If using Java 8, you can print values less than the average very simply
lesserAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);
upperAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);

Sum of ten random numbers

So far, my code looks like this:
import java.util.Random;
public class StatsCalculator
{
public static void main(String[] args)
{
Random r = new Random();
System.out.println("The ten random values are: ");
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
}
int randomint[];
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
}
}
When I run this code, there's an error message come up that say's the following: "variable randomint might not have been initialized, for (int i : randomint)
Try this:
int sum=0;
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
sum = sum + randomint ;
}
System.out.println("Sum = " + sum);
Place all the randoms within an array and then sum them:
Random r = new Random();
System.out.println("The ten random values are: ");
int[] values = new int[10];
for(int i = 0; i < 10; i++) {
int randomint = r.nextInt(10);
values[i] = randomint;
System.out.print(" ," + randomint);
}
int sum = 0;
for(int i : values) {
sum += i;
}
System.out.println("Sum = " + sum);
Your array randomInt is defined as an array but elements are never added to it, then you try iterate through it and there's nothing there.
Initialise it
int[] randomInt = new int[size];
then create elements in it. It looks like you should move this to before the first array and add all the random int you create.
The error is telling you everything: "variable randomint might not have been initialized, for (int i : randomint)"
In your head, you should hear this dialog:
Hmm, why is it telling me randomint might not have been initialised? Have I initialised it?
I better check this randomint...oh, here it is:
int randomint[];
How do I initialise it...the docs...the docs...THE DOCS!
Here it is:
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
// create an array of integers
int[] anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialised.
Fine, let's add this:
int randomint[] = new int[10];
compile...run...
errr, why is the sum 0 if I can see random numbers?
(reads the docs again)
Right, need to store those random ints in my array, phew, one more change:
Random r = new Random();
System.out.println("The ten random values are: ");
int randomint[] = new int[10];
for(int i=0; i<10; i++)
{
randomint[i] = r.nextInt(10);
System.out.print(" ," + randomint[i]);
}
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
Uff, next time someone asks similar question on SO, I might be able help them. First thing I'll say is to read the docs :)

Generating data for an array via Random class and sorting

Use the Random class to get numbers from 0 to 99 and store them into the array. Use a for loop to get each random number, store each into the array, and print each value.
Then use the bubble sort to sort the array, and print out the stored array.
here is my program
import java.util.Random;
public class Randomness
{
public static void main(String[] args)
{
Random randomNum = new Random();
for (int number = 0; number <= 99; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
int numValues = num;
int [] values = new int[numValues];
boolean swap;
do
{
swap = false;
int temp;
for (int count = 0; count < numValues-1; count++)
if (values[count] > values[count+1])
{
temp = values[count];
values[count] = values[count+1];
values[count+1] = temp;
swap = true;
}
} while (swap);
System.out.print(values[count] + " ");
}
}
}
i get error
System.out.print(values[count] + " "); array required, but Random found.
please help!
You aren't creating any random values in your array. You are creating an array of random length (between 0 to 99). You need to initialize each element of your array with a random:
Random randomNum = new Random();
int numValues = 100;
int[] values = new int[numValues];
for (int number = 0; number < numValues; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
values[number] = num;
}
Then do the bubble sort.

Categories