-2

Im trying to shorten my code by using loop somehow for the println statements. Instead of printing individual statements for name and height, is there another way of doing this with the same format?:

           System.out.println("Name: " + p1.getName() + "\nHeight: " + p1.getMeasure()+" cm");
           System.out.println("Name: " + p2.getName() + "\nHeight: " + p2.getMeasure()+" cm");
           System.out.println("Name: " + p3.getName() + "\nHeight: " + p3.getMeasure()+" cm");
default
  • 13
  • 4

3 Answers3

2

Just use a foreach loop:

for( Measurable pers: measureList) {
    System.out.println("Name: " + pers.getName() + "\nHeight: " + pers.getMeasure()+" cm");
}
bb1950328
  • 1,403
  • 11
  • 18
2
Arrays.stream(measureList).forEach(p->System.out.println("Name: " + p.getName() + "\nHeight: " + p.getMeasure()+" cm"));
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Java has like the very most programming languages several constraints to loop over "something". Try to google terms like java for loop, java for in loop, java while loop and java do while loop.

For your case a simple for loop should make it:

for(int i = 0; i < measureList.length; i++) {
  Person p = measureList[i];
  System.out.println("Name: " + p.getName() + "\nHeight: " + p.getMeasure()+" cm");
}

The for loop needs three things:

  • int i = 0: this is called once before the loop starts. we use it to initialize a counter and name it i(for index)
  • i < measureList.length: as long as this statement is true, the for loop will execute, otherwise it goes to next statement after the for loop. we use it to make sure, that the for loop is executed as long as the index i is smaller than the index of the last element in the array
  • i++: this will be executed after each loop. we use it to increment the index i for each loop

This results in a for loop with an index i that increments every loop until the end of the array is reached. Inside the for loop we can access the element in the array with the index.

0x4b50
  • 629
  • 6
  • 18