-6

I'm very new to Java, and have been following step-by-step guides online. However, I was unable to run this chunk of codes though I followed exactly what was taught and I got compile time errors.

my code:

public class HelloWorld {
public static void main(String[] args) {
    String[] family = {"Tricia", "ALbert", "Edwin"};
    for(String name = family) {
        System.out.println(name);
    }
  }
}

Hope could get some guidance here to show me where went wrong. I also notice I'm very bad with symbols and special characters.

I'd appreciate a lot for your help and precious time. Good day.

Farshad
  • 3,074
  • 2
  • 30
  • 44
  • 2
    Please include code and errors in the **text** of your question. Don't post them as links and/or screenshots. – khelwood Apr 04 '16 at 16:19
  • Possible duplicate of [Enhanced For Loop - Array of Objects](http://stackoverflow.com/questions/9530699/enhanced-for-loop-array-of-objects) – david Apr 04 '16 at 16:21
  • 1
    Possible duplicate of [Java for loop syntax: "for (T obj : objects)"](http://stackoverflow.com/questions/7763131/java-for-loop-syntax-for-t-obj-objects) – Eray Balkanli Apr 04 '16 at 16:32
  • Also, you can use `System.out.println(Arrays.toString(array))` to print the array. It is in the standard library. – ifly6 Apr 04 '16 at 22:53
  • Sorry, first time using Stack Overflow here. Will keep that in mind, @khelwood. – IceLemonTea Apr 05 '16 at 14:18

5 Answers5

4

The proper syntax for this kind of for loop is

for(String name : family)

Instead of what you have

for(String name = family)
NAMS
  • 983
  • 7
  • 17
0

use the "enhanced for loop":

for(String name : family) {
     // do stuff with name
}
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145
0

You have two possible ways:

1.-

for(String name : family) {
     // do stuff with name
}

2.-

final int len = family.length;
    for(int i=0; i<len; i++) {
         System.out.println(family[i]);  //where family[i] is the string at the give index
         // do stuff with name
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Just use this.

for(int i =0; i < family.length; i++)
{
   System.out.println(family[i]);
}

This will loop through the array and what ever the value of i is, will be the index of the array that is printed.

IE: index [0] is "tricia", index[1] will be "Albert" and so on.

Aaronward
  • 129
  • 2
  • 11
0

You can loop through the elements of an array in a couple of ways.

1. Standard for loop

for(int i = 0; i < family.length; i++){
  System.out.println(family[i]);
}

This is a standard for loop that iterates through each element of the array and prints each value.

2. Enhanced for loop

for(String value : family){
  System.out.println(value);
}

This is what you were trying to do in your sample, but you had = instead of :

Both work the same way to get the values of the array

Dan
  • 2,020
  • 5
  • 32
  • 55