Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created October 31, 2009 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jutememo/222952 to your computer and use it in GitHub Desktop.
Save jutememo/222952 to your computer and use it in GitHub Desktop.
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