You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
Videos
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T> here - usually ArrayList<T>, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T> to start with.
Use LinkedList instead. Than, you can create an array if necessary.
There is a NullPointerException because you declared but never initialized the array.
You can dynamically declare an array as shown below.
int size = 5; // or anyother value you want
int[] array = new int[size];
Or you use a list. Which allows to dynamically change the size. E.g:
List<Integer> list = new ArrayList<>();
list.add(5); //adds number 5 to the list
int number = list.get(0); // Returns Element which is located at position 0 (so in this example in number will be "5");
i do not want the array to have a specific size because each time the size must be different.
Arrays in Java have fixed size. Once declared, you cannot change it. If you try to force you way. You are creating a new array each time. Please do not create array1 to arrayN for any reasons.
If you want dynamic size, which can stretch and shrink. You are looking for ArrayList. ArrayList in Java is easy to use.
ArrayList<Type> arrayList = new ArrayList<>();
or
List<Type> arrayList = new ArrayList<>();
but when am trying the below code there is an error on myarray5
And I guess that would be an ArrayIndexOutOfBoundsException because your loops based on array1's length, but your other arrays like array5 is having different length.
Well, in your use case, you know exactly how many numbers you need. Look up how to find the number of odd numbers between two number based on your minimum and maximum. Then just allocate that many:
int closestMin = minimum % 2 == 0 ? minimum + 1 : minimum;
int closestMax = maximum % 2 == 0 ? maximum - 1 : maximum;
int numberOfOdds = ((closestMax - closestMin) / 2) + 1;
int[] arr = new int[numberOfOdds];
....
You can find out how many elements will be stored in the array then construct the array to be that size:
import java.util.Arrays;
public class Practice {
static int[] oddNumbers(int minimum, int maximum) {
int x = 0;
for(int i = minimum; i <= maximum; i++){ //
if(i % 2 != 0){ ////
++x; ////// Find the element count
} ////
} //
int[] arr = new int[x]; // Construct array with the length of the element count
x = 0; // Reset X (Just to avoid creating a new control variable)
for(int i = minimum; i <= maximum; i++){
if(i % 2 != 0){
arr[x] = i;
++x;
}
}
return arr;
}
public static void main(String[] args) {
int min = 3, max = 9;
System.out.println(Arrays.toString(oddNumbers(min, max)));
}
}
data[10] = {10,20,30,40,50,60,71,80,90,91};
The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element.
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used.
Even if you correct the syntax, accessing data[10] is still incorrect (You can only access data[0] to data[9] because index of arrays in Java is 0-based). Accessing data[10] will throw an ArrayIndexOutOfBoundsException.
Try
data = new int[] {10,20,30,40,50,60,71,80,90,91 };
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
int[] myIntArray = new int[3]; // each element of the array is initialised to 0
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
For classes, for example String, it's the same:
String[] myStringArray = new String[3]; // each element is initialised to null
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
There are two types of array.
One Dimensional Array
Syntax for default values:
int[] num = new int[5];
Or (less preferred)
int num[] = new int[5];
Syntax with values given (variable/field initialization):
int[] num = {1,2,3,4,5};
Or (less preferred)
int num[] = {1, 2, 3, 4, 5};
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
Multidimensional array
Declaration
int[][] num = new int[5][2];
Or
int num[][] = new int[5][2];
Or
int[] num[] = new int[5][2];
Initialization
num[0][0]=1;
num[0][1]=2;
num[1][0]=1;
num[1][1]=2;
num[2][0]=1;
num[2][1]=2;
num[3][0]=1;
num[3][1]=2;
num[4][0]=1;
num[4][1]=2;
Or
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
Ragged Array (or Non-rectangular Array)
int[][] num = new int[5][];
num[0] = new int[1];
num[1] = new int[5];
num[2] = new int[2];
num[3] = new int[3];
So here we are defining columns explicitly.
Another Way:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
For Accessing:
for (int i=0; i<(num.length); i++ ) {
for (int j=0;j<num[i].length;j++)
System.out.println(num[i][j]);
}
Alternatively:
for (int[] a : num) {
for (int i : a) {
System.out.println(i);
}
}
Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials
I have participated in many coding competitions but I'm unable to pass all the test cases just because of this problem. I don't know how to initialize an array with unknown size. I tried using
arr=malloc(size*sizeof(int));
But at the end it shows segmentation fault. Can someone explain why?