Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

java add int to int[]

How do I add a int to a int [] in Java. I want to do something like:

int limit = 10;
int[]array = {1, 9, 4, 20, 10, 20, 44};
int[]tooHigh;
            for (int i = 0; i < array.length; i++) {
                for (int j = 1; j < array.length - i; j++) {
                    if (array[j] < array[j - 1]) {
                        temp = array[j - 1];
                        array[j - 1] = array[j];
                        array[j] = temp; 
if (array[j]>10){tooHigh.add(array[j))

                    }

                }
            }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

simply, you cann’t as the array is of fixed size, its size cannot be modified once declared and you didn’t initialize that array called tooHigh which can result in some error if you try to access its member as it didn’t reserve any space in memeory as you didn’y type tooHigh = new int[size];

what you want to use is ArrayList for you mission.

so instead of:

int[]tooHigh;

write:

ArrayList<Integer> arrayList = new ArrayList<>();

and don’t forget to type :

import java.util.ArrayList;

at the beginning of the file. so that you can write :

    arrayList.add(15);
    arrayList.add(10);
    arrayList.add(30);
    arrayList.add(5);
    arrayList.add(-1);
    arrayList.add(5);

and this is some example code to add and loop over the ArrayList

public static void main(String[] args) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    arrayList.add(15);
    arrayList.add(10);
    arrayList.add(30);
    arrayList.add(5);
    arrayList.add(-1);
    arrayList.add(5);
    
    for (Integer integer : arrayList)
        System.out.println(integer);
}

and this is the output:

15
10
30
5
-1
5

look how simple is that!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading