Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced for loop problem

Tags:

java

foreach

Why is my enhanced loop not working?

Vector<String> v = new Vector<String>();
          v.add("one"); 
          v.add("two");
          v.add("three");
          for(String str : v){
              System.out.println(v);
          }

1 Answers

The problem with you code is that in the for statement instead of this:

          for(String str : v){
              System.out.println(v);
          }

you should have this:

          for(String str : v){
              System.out.println(str);
          }

making the final code like this:

Vector<String> v = new Vector<String>();
          v.add("one"); 
          v.add("two");
          v.add("three");
          for(String str : v){
              System.out.println(str);
          }

In simple terms you are giving the value of v to a string called str, then you print it using System.out.println(...) and this loop will continue until there are no more items left from v to print.

Hope it helps.

like image 123
Carlos Avatar answered Apr 29 '26 23:04

Carlos