今天第一天接触java,遇到了一个打印输出数组的基本问题。之前曾学过c,首先想到的第一个方法肯定是
public class hello {
public static void main(String[] args) {
int ns[] = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
System.out.print(ns[i]);
}
}
}
后来发现原来还可以使用for_each进行遍历,语法规则为:
for(数据类型 变量名:数据所在的集合) 上代码
public class hello {
public static void main(String[] args) {
int ns[] = { 1, 4, 9, 16, 25 };
for(int n:ns){
System.out.println(n);
}
}
}
后来参考了某大佬的博客,其实还有更快的方法,利用Arrays.tostring(),直接输出数组内容
public class hello {
public static void main(String[] args) {
int ns[] = { 1, 4, 9, 16, 25 };
System.out.println(Arrays.toString(ns));
}
}