Hello, I want to do this procedure but I don't know how. this is python:
num = 7
for i in range(1,num+1):
numbers = []
numbers.append(i)
for x in numbers:
print(x,end = " ")
here the code in java but it doesn't work for me
int num = 5;
for(int i = 0; i < num; i++) {
int array[] = {};
array.append[i]
As you can see, I can't fill that array like I did with python.
It would be something like this, where you first size the array
numbers
based on the variablenum
and add the values to the arraynumbers
, then print the values stored in the array:what happens is that python works with lists so it is not necessary to enter the size, in java it should be like this
or another solution could be this, if instead of lists you want to do it with arrays:
You can use two for loops as usual in java:
If you want to do it in another way using Java 8, you can do it in the following way:
Here is the example so you can run it online.
There are five things, first you need to close a brace (
}
), the second is that the reason why this does not work for you:It is because you are creating the array within the loop and then it is being destroyed , what happens is your array, when created within the for , will only exist within the for.
The third thing is that, keep in mind that
python
things work very differently,pyhon
when you declare aarray
you do not need to specify the number of spaces you want it to have .In
java
this it is different, because for that type of arrays you must always define a size , therefore they are called fixed memory arrays , and there is nothing you can do so that you can use them as dynamic memory arrays , that is to say that once you set the values that the array is going to have or the amount of spaces it is going to havearray
, the only way to change the amount of memory or spaces that the array is going to use is by redeclaring it, which directly empties the memory.So that you understand me better, the fourth error is that you have this:
That is wrong, it must be corrected, since they
[]
do not go after the name of the variable, they go after the type in this way:Now that that little detail is corrected, keep in mind that when you use curly braces (
{}
) after the equal, it's because what you're trying to do is assign values directly to the array, so you could do something like this and it would work:However when you leave the keys empty:
It is the equivalent of saying that you are not going to save anything in your array and you cannot save anything , that is, you are defining your array with a memory space of
0
elements:That would be the other way of declaring an array with
x
spaces in memory, but without directly assigning values, that is, it would be like having empty spaces in memory assigned that you can later fill.The fifth problem is that in this line you forgot a
;
at the end, I have added it for you:That said, let's make the correction to your code:
If you want to see the result you can then print later
array
: