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))
}
}
}
CodePudding user response:
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!
CodePudding user response:
Use ArrayList so you will be able to do add
List tooHigh=new ArrayList(Integer);
tooHigh.add(array[j])