-1

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);
} 
smac89
  • 26,360
  • 11
  • 91
  • 124
user11124425
  • 881
  • 4
  • 17

6 Answers6

3

try this:

int[] notes = new int[7];

for(int i=0;i<7;i++){
  notes[i] = 0;
} 
Doctor Parameter
  • 944
  • 2
  • 9
  • 18
  • 3
    This is the literal translation of the Python code, but note that in Java, the array already has 0s in it when you create it, so the loop here is redundant. – kaya3 Nov 12 '19 at 21:12
3

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);
}
PauMAVA
  • 751
  • 7
  • 14
  • 1
    It won't throw a NPE unless you initialise it as `null`. If you don't initialise it, then the code won't compile. – kaya3 Nov 12 '19 at 21:11
2

You can also do like this.

Arrays.fill(notes, -1);// But notes has to be declared.

or

int[] notes = {0,0,0};
PythonLearner
  • 1,174
  • 2
  • 16
2

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.

Ben P.
  • 44,716
  • 5
  • 70
  • 96
1

You need to use an assignment operation.

notes[i] = 0;

Vitalie
  • 19
  • 1
1

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
Boris Zhguchev
  • 306
  • 4
  • 12