R
R
Rudy99662021-09-26 20:18:38
Java
Rudy9966, 2021-09-26 20:18:38

How to access the second value in an array?

There is an array:

private Brus[] arr = new Brus[3];
  private int count = 0;
  {
    arr[0] = new Brus("Брусок", 500);
    arr[1] = new Brus("Брусок1", 350);
    arr[2] = new Brus("Брусок3", 5500);
    count = 3;
  }

The second value is the weight. There is a cycle. How to refer to the second value, i.e. the weight in the loop, so that it adds the weight of each element and stores it in another variable?

public void calc() {
     for (int i = 0; i < count; i ++) {
       	
        int calcTotalWeight;
      }
   }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-09-26
Hasanly @azerphoenix

Good afternoon.
First of all, I recommend using the search and only after that ask a question.
Regarding your question:
Let's say you have a class

class Brus {
public String name;
public String weight;
}

There is also an array private Brus[] arr = new Brus[3];, which, by the way, is dynamically initialized.
{
    arr[0] = new Brus("Брусок", 500);
    arr[1] = new Brus("Брусок1", 350);
    arr[2] = new Brus("Брусок3", 5500);
    count = 3;
  }

Judging by this code, I will assume that you need to calculate the weight of all the beams. I will not give you a complete answer so that you can think for yourself, but only write what needs to be done.
public void calc() {

int calcTotalWeight;
                               // получаем длину массива
     for (int i = 0; i < arr.length; i ++) {
       // получаем вес текущего блока
       int weight = arr[i].weight;
      // после получения веса текущего бруса суммируем его значение к общему весу calcTotalWeight
      }
   }

Here is a similar question - https://stackoverflow.com/questions/3123086/access...
By the way, the question specifies the use case forEach. And also using a getter instead of accessing a public field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question