你能帮我理解发生了什么吗?我拿了一本书Core Java。第一个变体来自那里。第二个变体是我尝试编译程序。我有:java 版本“1.7.0_21”Java(TM) SE 运行时环境(构建 1.7.0_21-b11)Java HotSpot(TM) 64 位服务器 VM(构建 23.21-b01,混合模式)
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]);
}
}
结果:
Welcome.java:16: error: incompatible types
System.out.println(greeting[g]);
^
required: int
found: String
1 error
如果我更改我的代码:
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]);
}
}
结果是:
Welcome.java:15: error: incompatible types
for (int g: greeting)
^
required: int
found: String
1 error