I have to generate prime number. For this reason I have to initialize all array elements to -1. From c/c++, I came to know I have to initialize them by using a for loop. Please see the code below
public static void main(String[] args){
final int SIZE = 1000;
int[] intArray = new int[SIZE];
Arrays.fill(intArray, -1);
for(int i=0; i<SIZE; i++){
intArray[i] = -1;
}
for(int i = 0; i<SIZE; i++){
System.out.println(intArray[i]);
}
}
In java is there any better way to do this?
Well, Arrays.fill(intArray, -1); already fills your array, so there's no need for the redundant for loop following that statement.
You can also just remove your final int SIZE, and say int[] intArray = new int[1000];. When you need to get the length/size of the array, you can just say intArray.length.
You can only use Arrays.fill(int[] a, int val) method like this -
Arrays.fill(intArray, -1);
The Arrays.fill() populates the array - intArray with the specified value val. So you don't need to initialize the intArray using the for loop.
And one more thing, in c++ it is also possible to initialize array with some value like this, without using the for loop. See here
Related
Here is an exercise:
Write an algorithm that declares and fills an array of 7 values numerics, bij putting the values to 0.
In Python I have to do this:
note = []
for i in range(7):
note.append(0)
print( note )
I have tried below in Java... I am obliged to use an arrayList?
I would like the do with an array empty.
int[] notes;
for(int i=0;i<7;i++){
notes.add(0);
}
try this:
int[] notes = new int[7];
for(int i=0;i<7;i++){
notes[i] = 0;
}
When declaring your notes array you must initialize it and specify the length of it. If not it will throw a compilation error. Proceed as follows:
int[] notes = new int[7]; //Declare the size of the array as 7
for(int i=0;i<7;i++){
notes[i] = 0; //Iterate the positions of the array via the variable i.
}
If you want to use an ArrayList:
List<Integer> notes = new ArrayList<Integer>(); //You don't have to define the length.
for(int i = 0; i < 7, i++) {
notes.add(0);
}
You can also do like this.
Arrays.fill(notes, -1);// But notes has to be declared.
or
int[] notes = {0,0,0};
For the special case of int and a desired value of 0, you don't even have to write out the loop assignment. You just need this:
int[] notes = new int[7];
This will create an array of ints, each with the Java default value of 0.
You need to use an assignment operation.
notes[i] = 0;
Another option - using streams:
int[] notes = IntStream.range(0, 7).map(i -> 0).toArray();
But if you need exactly 0, you can simply do it like:
int[] notes = new int[7]; // but it for 0 only
So I've got this method:
public static int[] select(int maxWidth, int maxHeight) {
int rHeight = StdRandom.uniform(0, maxHeight);
int rWidth = StdRandom.uniform(0, maxWidth);
return new int[] {rHeight, rWidth};
}
And I'm not advanced enough to work with it on the right way.
I've got a second method where I want to execute 'select' several times. My idea was to do it with a for-loop like that (in which 'n' is a int):
for(int i = 0; i < n; i++){
select(h, w);
}
But now I don't know how to save the result from this for-loop in an 1d-array, since I will always get an error when trying to save like that:
int[] a = new int[select(h, w)];
I'm very aware that this looks very strange and wrong but I just don't know how to do it in the right way and I don't know for what I have to search on google.
Here is a way you could do it:
int[][] a = new int[n][];
for(int i = 0; i < n; i++){
a[i] = select(h, w);
}
Basically this code creates a 2d array, then in the for loop, adds the result of select to each element of the array.
I don't think you can do this in a 1D array, if you want to run select multiple times, and each time it returns an array, you'll have to have an array of arrays. If you are adamant about having a 1D array to store the answers, you'll have to implement a tuple class, although I think you're better off just doing a 2D array the way Sub 6 Resources showed.
int[] combined = new int[n*2];
for(int i = 0; i < n; i++){
int a[] = select(h, w);
System.arraycopy(a, 0, combined, i*2, 2);
}
I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended
I am new to the concept of arrays in java, and as part of an assignment, I am required to create a 10 row by 3 column integer array and populate it with a for loop. I have the following.
public class arrays{
int arr[][][] = new int [10][10][10];
for(int i=0;i<arr.length;++i)
{
for(int j=0;j<arr[i].length;++j)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
am I on the right track?
You are actually declaring a 3-dimensional array.
You should instead be declaring int[][] arr = new int[10][3];.
You can then assign values as follows: arr[i][j] = 42;
Note also that when instantiated, the initial values in the array are 0.
The way of creating array in java is simple and I see you know that but for your problem applicable array might be different. Try that one
int arr[][] = new int [10][3];
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
arr[i][j] = your_integer_value;
}
}
Hi i'd like to populate array in Java. I'm trying to do it on easily way
int[] tab = null;
for(int i=0; i<5; i++)
{
tab[i]=i;
}
Why this constructions not working ?
error: null pointer exception
This is how you implement it
int[] tab = new int[5];
for(int i=0; i<tab.length; i++)
{
tab[i]=i;
}
Dynamic allocation means you should be using one of the Collection instances, such as a List. If you have some constraint (such as homework rules) that says you must use an array, then you have to do the following:
declare and instantiate the array to some arbitrary size: int[] intArray = new int[20];
during the addition of the elements, check if the index is equal to the length - 1: if(index == length - 1) , and if true,
create a temporary array of a size that is some multiple of the original array's size (usually 2x) int[] temp = new int[intArray.length*2];
copy the elements from the original array to the temp array
reassign the temp variable value to the original: intArray = temp;
after the loop, create a new array that is the correct length and copy all values from the original to the new one. (this is because the size will most certainly be wrong -- the length will be more than the number of elements).
In pseudo code, it looks like this:
int[] intArray = new int[20];
int index = 0;
loop:
if(index >= intArray.length - 1){
int[] temp = new int[intArray.length * 2];
copyAll: intArray->temp // use System.arrayCopy
intArray = temp;
}
intArray[index] = value;
index++;
endloop:
// resize because intArray will likely be too big
int[] temp = new int[index];
copyAll intArray -> temp;
intArray = temp;
As you can see, it's much, much nicer to use the Collection framework:
List<Integer> intList = new ArrayList<Integer>();
loop:
intList.add(value);
endloop
Here is how I would implement this array in the simplest way possible:
int[] tab = new int[]{0, 1, 2, 3, 4};
Your code doesn't work because you never create a new object to hold the elements of the array, it just creates space for a reference to that object. Before you can reference the object using
tab[i]
you must create a new object like this:
tab = new int[5];
So, if you really want to implement this variable in a for loop for whatever reason, here's how you should do it:
final int ARRAY_SIZE = 5;
int[] tab = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE; i++){
tab[i] = i;
}
Now, if you want to increase the number of elements in your array, you just need to change the ARRAY_SIZE variable.
You need to initialize your array before you use it:
int[] tab = new int`[5];
If you need something that is dynamicaly allocated use something like Vector or ArrayList:
For example:
ArrayList<Integer> list = new ArrayList<Integer>();
int elements_to_add = 5;
for(int i=0; i<elements_to_add; i++)
{
list.add(new Integer(i) );
}
Despite the fact that you declare this array and pass it null, you don't create any object here. You have only a reference to null. That's the reason of your error. What you have to do is initialize this array like int []myArray = new int[5];
Something like this should work :
int[] tab = new int[5];
for(int i=0; i<5; i++){
tab[i] = i;
}