java在字符异常处理中的应用
我是这里的新手 我有下面的代码,它运行得很好,但当我输入一个特殊字符(@、%、*等)时,它必须抛出异常,所以我如何才能做到这一点,有人能帮助我,因为我是一个新手程序员吗 /*用于检查值的代码*/java在字符异常处理中的应用,java,Java,我是这里的新手 我有下面的代码,它运行得很好,但当我输入一个特殊字符(@、%、*等)时,它必须抛出异常,所以我如何才能做到这一点,有人能帮助我,因为我是一个新手程序员吗 /*用于检查值的代码*/ import java.io.BufferedReader; import java.io.InputStreamReader; public class CheckVal { public static void main(String args[]) { int i=0;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CheckVal
{
public static void main(String args[])
{
int i=0;
double x=0;
System.out.println("Enter your angle");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
x=Math.sin(Math.toRadians(i));
System.out.println(x);
if(x>=0 && x<=0.5)
{
ButtonBackground frame = new ButtonBackground("green");
//frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setResizable(false);
frame.setVisible(true);
}
else{
ButtonBackground frame = new ButtonBackground("red");
//frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setResizable(false);
frame.setVisible(true);
}
}
}
据我所知,它已经有了,但你正在抓住它。作为一项建议,尽量避免使用神奇宝贝try-catch方法(“通过捕获一个通用的
异常来捕获所有人!”)
通过做
try {
//your code
} catch (Exception e) {
}
您正在捕获try中的代码可以抛出的各种异常,而没有机会知道出了什么问题。如果您的应用程序失败了,这将成为一场噩梦,因为它没有“中断”,但没有执行您希望它执行的操作
特别是,您希望得到一个整数,如果您得到特殊字符,您希望抛出一个异常。IllegalArgumentException似乎适合您的特殊需要,因为特殊字符毕竟是非法参数。我建议不要采用这种输入法:
System.out.println("Enter your angle");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e);
}
您可以尝试这样做:
System.out.println("Enter your angle");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
}
catch(NumberFormatException e)
{
throw new IllegalArgumentException();
}
如果我没弄错的话,那就是你想要的
作为旁注,请记住捕获IllegalArgumentException,这样它就不会向上传播。为了更好地管理这一点,请尝试创建一个函数,该函数读取输入并返回int,或者在给定情况下引发异常
private int readEntry() throws IllegalArgumentException {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
} catch(NumberFormatException e) {
throw new IllegalArgumentException();
}
}
然后,您可以在主函数中调用它,并执行您认为必要的任何操作。这也提高了可读性
int input = readEntry(); //Surround this with a try-catch and catch the IllegalArgumentException if you want to control it.
请不要张贴代码墙。想出一个更好的办法,解释得很好!感谢:)作为旁注,我可以提出的另一个建议是尽量重用代码。例如,除颜色设置外,if else
块包含几乎相同的代码。您可以只使用该代码的一个实例,并以color currentColor=x.equals(“绿色”)开头定义要使用的颜色?Color.GREEN:Color.RED
(通常称为“inline if”,如果您不熟悉它,请使用if else
),然后您可以使用该currentColor
变量调用setColor和setBackground方法。这样你就可以用更少的代码完成同样的任务。谢谢你宝贵的建议
int input = readEntry(); //Surround this with a try-catch and catch the IllegalArgumentException if you want to control it.