class Person { String name; int age; public String toString() { String s = ""; s += this.name; s += "(" + this.age + ")"; return s; } Person(String name, int age) { this.name = name; this.age = age; } }
import java.util.Scanner; public class Teishutsu13_2 { public static int sentinelSearch(Person[] x, Person key) { x[x.length - 1] = key; int i = 0; while (x[i] != key) { i++; } return i; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); Person[] x = new Person[10]; x[0] = new Person("あいだ", 19); x[1] = new Person("いいだ", 25); x[2] = new Person("うしお", 30); x[3] = new Person("かけい", 21); x[4] = new Person("きすぎ", 20); x[5] = new Person("くるま", 19); x[6] = new Person("さなだ", 18); x[7] = new Person("しむら", 22); x[8] = new Person("すどう", 23); x[9] = new Person("なし", 0); System.out.print("名前を入力してください:"); String name = sc.next(); System.out.print("年齢を入力してください:"); int age = sc.nextInt(); Person key =new Person(name, age); int idx = sentinelSearch(x, key); if (idx == x.length - 1) { System.out.println("その値は存在しません"); } else { System.out.println("その値はx[" + idx + "]にあります"); } System.out.println(idx); } }
名前と年齢の組をキーとして学生を線形探索によって検索し結果を表示したいのですが、どの組を検索しても必ず探索できず見つけることができません。試しにidxを表示させてみると番兵として置いた9が表示されました。おそらく入力した組と配列の中の組とが一致せず最後まで検索され9と表示されているのだと思います。しかしどこが間違っているのかわかりません。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/01/14 07:09