Posted by 신의섭 on August 19, 1997 at 13:09:20:
In Reply to: [질문] Hashtable에서... posted by 최재영 on August 19, 1997 at 01:25:31:
제가 올려놓으신 소스코드를 약간 손봐서 테스트해보니 잘되더군요.
주로 고친 부분은 input에서 '\n'을 '\r'로 고쳤고, 그래도 자꾸 error가 나서 보니
equals() 메소드에서 charAt 메소드 수행시 OutofBound가 나오더라구요
그래서 아래의 소스와 같이 수정했습니다.
도움이 되시길...
----------------------------------------------
import java.util.Hashtable;
class man_info {
String name;
int n;
public man_info(String s) {
name = s;
n = s.length();
// System.out.println("C = "+n);
}
public int hashCode() {
return (int)name.charAt(0);
}
public boolean equals(Object compare) {
man_info temp = (man_info)compare;
System.out.println("this " + this.name + this.n);
System.out.println("temp " + temp.name + temp.n);
System.out.println("n = " + n);
for(int i = 0; i < (temp.n - 1); i++) {
System.out.println(i);
if(this.name.charAt(i) != temp.name.charAt(i)) {
return false;
}
}
return true;
}
} // end of class man_info
class hash {
public static void main(String args[]) throws java.io.IOException {
Hashtable hashtable = new Hashtable();
man_info man[] = new man_info[5];
char search;
man[0] = new man_info("tiger"); // 얘네들의 length는 순수한 글자들의
man[1] = new man_info("elephant"); // 길이만 리턴됩니다. tiger = 5 ...
man[2] = new man_info("javaman");
man[3] = new man_info("mazinga");
man[4] = new man_info("jaeyoung");
for(int i = 0; i < 5; i++)
hashtable.put(man[i], man[i]);
System.out.print("Input characters for the name : "); // println을 print로-- 보기 좋으라고
StringBuffer stringtemp = new StringBuffer();
// System.out.println(stringtemp.length());
while((search = (char)System.in.read()) != '\r') {
// System.out.println(search);
stringtemp.append(search);
// System.out.println(stringtemp.length()); // 그런데 여기서의 길이는
} // 1이 더 많이 나오죠. tig = 4....
System.out.println(stringtemp.length()); // test 해보니 딱 맞아요..
String s = new String(stringtemp.toString()); // 물론 String으로 바꿔도 마찬가지..
man_info searched = new man_info(s);
// System.out.println("l = " + s.length());
man_info result = (man_info)hashtable.get(searched);
if(result == null)
System.out.println("Nothing..."); // 항상 result가 널이라는 군요....거참..
else
System.out.println(result.name);
}
}