Skip to content

Instantly share code, notes, and snippets.

@mokomokohitsuzi
Created January 12, 2017 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokomokohitsuzi/c121258f5d5ae526112e43cb32f226bd to your computer and use it in GitHub Desktop.
Save mokomokohitsuzi/c121258f5d5ae526112e43cb32f226bd to your computer and use it in GitHub Desktop.
新・明解Java入門 演習7-15
import java.util.Random;
import java.util.Scanner;
public class En07_15 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
Random rand = new Random();
System.out.print("配列aの要素数:");
int n = stdIn.nextInt();
int[] a = new int[n];
// 配列に値を代入する。
for (int i = 0; i < a.length; i++) {
a[i] = rand.nextInt(10) + 1;
}
System.out.println("配列aへランダムに1~10までの値を代入しました。");
// 表示
for (int i = 0; i < a.length; i++) {
System.out.printf("a[%d] = %d\n", i, a[i]);
}
int sum = sumOf(a);
System.out.printf("合計は%dです。", sum);
}
// 合計を求めるメソッド
static int sumOf(int[] a) {
// 合計変数sum
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment