質問編集履歴

1

入力値が3ならば配列を3つ作るが出来ました。

2019/03/30 23:05

投稿

whitehorse85921
whitehorse85921

スコア34

test CHANGED
File without changes
test CHANGED
@@ -30,17 +30,79 @@
30
30
 
31
31
  import java.util.Scanner;
32
32
 
33
- class Main{
34
33
 
35
- public static void main(Strint[]args){
36
34
 
37
- Scanner s=new Scanner(System.in);
35
+ public class Search{
38
36
 
39
- int n=s.nextInt();
37
+ static int search(int[] a, int n, int key){
40
38
 
41
- //以下、入力した数だけ配列を作りたいです。
39
+ int i=0;
42
40
 
41
+
42
+
43
-
43
+ while(true){
44
+
45
+ if(i==n)
46
+
47
+ return -1;
48
+
49
+ if(a[i]==key)
50
+
51
+ return i;
52
+
53
+ i++;
54
+
55
+ }
56
+
57
+ }
58
+
59
+ public static void main(String[]args){
60
+
61
+ Scanner stdIn=new Scanner(System.in);
62
+
63
+
64
+
65
+ final int num=5;
66
+
67
+ int[] x=new int[num];
68
+
69
+
70
+
71
+ System.out.println("いくつ配列を用意しますか?");
72
+
73
+ int layout=stdIn.nextInt();
74
+
75
+
76
+
77
+ for(int y=1; y<=layout; y++){
78
+
79
+ for(int i=0; i<num; i++){
80
+
81
+ System.out.print("x[" + i + "]:");
82
+
83
+ x[i]=stdIn.nextInt();
84
+
85
+ }
86
+
87
+ }
88
+
89
+ System.out.print("探す値:");
90
+
91
+ int ky=stdIn.nextInt();
92
+
93
+
94
+
95
+ int idx=search(x,num,ky);
96
+
97
+
98
+
99
+ if(idx==-1)
100
+
101
+ System.out.println("その値の要素は存在しません。");
102
+
103
+ else
104
+
105
+ System.out.println("その値は" + idx + "にあります。");
44
106
 
45
107
  }
46
108
 
@@ -52,7 +114,7 @@
52
114
 
53
115
  ### 試したこと
54
116
 
55
-
117
+ 例えば入力値が「3」の場合、配列を3つ作るは出来ました。ただ、3つ配列がある上で例えば「2」を線形探索すると上手く線形探索行えなかったです。
56
118
 
57
119
  ここに問題に対して試したことを記載してください。
58
120