Created
January 12, 2017 12:19
-
-
Save mokomokohitsuzi/c121258f5d5ae526112e43cb32f226bd to your computer and use it in GitHub Desktop.
新・明解Java入門 演習7-15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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