Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) throws Exception {
  5. Scanner sc = new Scanner(System.in);
  6. // 『アルゴリズムはじめの一歩完全攻略』
  7. //2-2 線形探索
  8.  
  9. int[] a = {72, 68, 92, 88, 41, 53, 97, 84, 39, 55};
  10.  
  11. int i, x, pos;
  12.  
  13. System.out.println("探したい数値を整数で入力してください");
  14. try{
  15. x = sc.nextInt();
  16. pos = -1;
  17.  
  18. for (i = 0; i < a.length && pos == -1; i++){
  19. if (a[i] == x){
  20. pos = i;
  21. }
  22. }
  23.  
  24. if(pos != -1){
  25. System.out.println(x + " は " + pos + " 番目にあります");
  26. }else{
  27. System.out.println(x + " は" + "見つかりませんでした");
  28. }
  29.  
  30.  
  31. }catch (InputMismatchException e){
  32. System.out.println("不正な入力です。整数を入力してください");
  33. }
  34.  
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement