Could you help me understand what's going on. I've taken a book Core Java. The first variant is from there. The second variant is my attempt to compile the progrm. I have: java version "1.7.0_21" Java(TM) SE Runtime Environment (build 1.7.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (String g: greeting)
System.out.println(greeting[g]);
}
}
The result:
Welcome.java:16: error: incompatible types
System.out.println(greeting[g]);
^
required: int
found: String
1 error
If I change my code:
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (int g: greeting)
System.out.println(greeting[g]);
}
}
The result is:
Welcome.java:15: error: incompatible types
for (int g: greeting)
^
required: int
found: String
1 error