java 问题求解释
中午写了一段代码,题目要求是比较两个字符串,假如字符串为空对象,产生异常。代码:public class Compare {
private String string_1;
private String string_2;
Compare(String string_1,String string_2){
this.string_1=string_1;
this.string_2=string_2;
}
void test(){ //两个字符串比较,如有空字符触发异常
try{
if(string_1.equals(string_2)){
System.out.println("string is equal.");
}
else {
System.out.println("string isn't equal.");
}
}
catch(NullPointerException e){
System.out.println("Please input two strings.");
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please input two strings:\n");
String string_1=br.readLine();
String string_2=br.readLine();
string_1=string_1.trim();
string_2=string_2.trim();
Compare compare=new Compare(string_1,string_2);
compare.test();
}
}
求大神指教错在哪了。。。