Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.Arrays;
import java.util.List;
/**
* 検索クラス
*/
public class Search {
private static List<Person> persons = Arrays.asList(
new Person("Tarou", "Tokyo"),
new Person("Jirou", "Osaka"),
new Person("Saburou", "Nagoya"));
// 見つからなかったときは、例外 Nothing を投げる
static Person find(String name) throws Nothing {
for (Person p : Search.persons) {
if (p.getName().equals(name)) {
return p;
}
}
throw new Nothing(name); // null の代わりに例外を投げる
}
public static void main(String[] args) {
try {
System.out.println(find("Tarou").getAddress());
System.out.println(find("Hanako").getAddress());
} catch (Nothing e) {
System.out.println(e.getMessage() + " ha imasen");
}
}
}
/**
* 「人」を表わすクラス
*/
class Person {
private String name;
private String address;
Person(String name, String address) {
this.name = name;
this.address = address;
}
String getName() {
return this.name;
}
String getAddress() {
return this.address;
}
@Override
public String toString() {
return this.name + ":" + this.address;
}
}
/**
* null に対応した例外クラス
*/
class Nothing extends Exception {
Nothing(String name) {
super(name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment