Skip to content

Instantly share code, notes, and snippets.

@mokomokohitsuzi
Created December 7, 2016 13:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokomokohitsuzi/ec42a1b5d0aa067cc4dddeef7d365b85 to your computer and use it in GitHub Desktop.
Save mokomokohitsuzi/ec42a1b5d0aa067cc4dddeef7d365b85 to your computer and use it in GitHub Desktop.
新・明解Java入門 演習6-7
import java.util.Random;
import java.util.Scanner;
public class En06_07 {
public static void main(String[] args) {
Random rand = new Random();
Scanner stdIn = new Scanner(System.in);
// 要素数
final int n = 12;
// 配列を宣言
int[] a = new int[n];
for (int j = 0; j < n; j++) {
a[j] = rand.nextInt(10);
}
System.out.print("配列aの全要素の値\n{ ");
for (int j = 0; j < n; j++) {
System.out.print(a[j] + " ");
}
System.out.println("}");
System.out.print("探す数値:");
int key = stdIn.nextInt();
int i;
for (i = n - 1; i >= 0; i--) {
if (a[i] == key) {
break;
}
}
if (i >= 0) {
// 探索成功
System.out.println("それはa[" + i + "]にあります。");
} else {
// 探索失敗
System.out.println("それはありません。");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment