gpt4 book ai didi

java - 具有增强 for 循环的字符串数组

转载 作者:行者123 更新时间:2023-12-02 05:38:53 27 4
gpt4 key购买 nike

这里需要一些建议,我正在尝试编码创建一个包含任意六个名字的字符串数组。 使用增强的 for 循环打印数组中的每个名称这是我所拥有的:

public class names {
private static String[] arrayString;
private static String[] names;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String[][]firstnames={
{"John", "Mary", "Harry", "Ray", "Sean", "Matthew" },
};

for (int row=0;row<firstnames.length;row++){
for(int col=0; col<firstnames[row].length; col++){
System.out.print(firstnames[row][col]+ " ");
System.out.println();
}
}
}
}

有人告诉我,您在循环条件中使用了固定值,而不是数组的长度。

最好使用数组的长度进行维护等

我花了很长时间试图弄清楚我哪里出了问题,据我所知我已经回答了这个问题。有人能指出我正确的方向吗?

最佳答案

如果我理解你的问题,那么我认为你想用增强的 foreach 来做一些事情像这样循环,

String[] firstNames = {"John", "Mary", "Harry", "Ray", "Sean", "Matthew" };
for (String name : firstNames) {
System.out.println(name);
}

根据 javadoc 链接,

When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

关于java - 具有增强 for 循环的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24701668/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com