Created
October 31, 2009 06:18
-
-
Save jutememo/222952 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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