异常处理,确保正常输入
/*
* Created on 2007-3-16
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.math.BigDecimal;
/**
* @author hp
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import javax.swing.JOptionPane;
public class TriangleJudge {
public static void main(String[] args) {
String first;
String second;
String third;
String result;
int n1;
int n2;
int n3;
first=JOptionPane.showInputDialog( "请输入第1条边长: ");
second=JOptionPane.showInputDialog( "请输入第2条边长: ");
third=JOptionPane.showInputDialog( "请输入第3条边长: ");
n1=Integer.parseInt(first);
n2=Integer.parseInt(second);
n3=Integer.parseInt(third);
result= " ";
if ((n1+n2> n3)&&(n1-n2 <n3))
{result=result+ "您输入的三条边长分别是: "+n1+ ", "+n2+ ", "+n3+ "; "+ "\nit can form a triangle ";
if((n1==n2)&&(n2==n3))
result=result+ "\ndengbian ";
else if((n1==n2)||(n2==n3)||(n1==n3))
result=result+ "\ndengyao ";
else result=result+ "normal ";}
else result=result+ "您输入的三条边长分别是: "+n1+ ", "+n2+ ", "+n3+ "; "+ "\nit cannot form a triangle ";
JOptionPane.showMessageDialog(null,result, "TriangleJudge ",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);}
}
//如何添加异常处理,确保输入的数据不为空,并且都是正数?
请教...
------解决方案--------------------例如:
n1=Integer.parseInt(first);
改为:
try
{
n1=Integer.parseInt(first);
}
catch(
NumberFormatException nfe)
{
//fuck,请输入整数
}
if(n1 <0)
{
//fuck,请输入正整数
}
------解决方案--------------------try{
n1=Integer.parseInt(first);
n2=Integer.parseInt(second);
n3=Integer.parseInt(third);
}catch(NumberFormatException e){
System.out.println( "输入含有非数字符号!!!! ");
}
if(n1 <=0)
{
//为非正数
}
------解决方案--------------------楼上的有道理
效率稍微有点低
如果该处理不存在瓶劲问题
可以这样做的