user298472
user298472

Reputation:

Enhanced for loop problem

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);
          }

Upvotes: 3

Views: 2209

Answers (1)

Carlos
Carlos

Reputation: 5445

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.

Upvotes: 9

Related Questions