Created
December 12, 2016 13:20
-
-
Save mokomokohitsuzi/a4d5ed26bd57ac4941dc251227da2c9c to your computer and use it in GitHub Desktop.
新・明解Java入門 演習6-12
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 En06_12 { | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
Random r = new Random(); | |
System.out.print("要素数:"); | |
int elements = s.nextInt(); | |
int[] lists = new int[elements]; | |
System.out.println("数字を入力して下さい。"); | |
for (int i = 0; i < lists.length; i++) { | |
System.out.printf("a[%d] :", i); | |
lists[i] = s.nextInt(); | |
} | |
System.out.println("ランダムに順番を入れ替えます。"); | |
int randoms; | |
int[] hokan = new int[elements]; | |
// ランダムに表示する | |
for (int i = 0; i < lists.length; i++) { | |
Roop: while (true) { | |
randoms = r.nextInt(elements); | |
// 配列を走査し、同じ値であればRoopからやり直す。 | |
for (int j = 0; j < i; j++) { | |
if (hokan[j] == randoms) { | |
continue Roop; | |
} | |
} | |
// 保管用の配列に現在の値を保存する。 | |
hokan[i] = randoms; | |
break; | |
} | |
// hokanに保存した数の順にlistsを表示。 | |
System.out.printf("a[%d] :%d\n", hokan[i], lists[hokan[i]]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment