答案1——不用foreach
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int z=0,a=in.nextInt();
int num[] = new int[a];
for (int i = 0; i < a; i++) {
num[a]=in.nextInt();
z+=num[a];
}
System.out.println(z);
}
}
答案2-用foreach————仅供参考,foreach用法见Java循环结构-java增强for循环
package ltd.mufengnet.hello;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int z=0,a=in.nextInt();
int []num = new int[a];
for (int i = 0; i < a; i++) {
num[i]=in.nextInt();
}
for (int i:num
) {
z+=num[i-1];
}
System.out.println(z);
}
}
这道题我认为完全没有必要用foreach,不过foreach用来遍历数组还是很好的= =
易错点:数组下标越界(报错信息出现index等字样)
注:foreach并不是foreach() 而是 for(声明语句 : 表达式)
仅供参考,如有更优解,可在评论区参与讨论
Comments NOTHING