java关于处理字符异常

标签 java

我是这里的新手 我有以下代码,它运行良好,但是当我给出特殊字符(@、%、* 等)作为输入时,它必须抛出异常,所以我怎样才能做到这一点,有人可以帮助我,因为我是新手程序员

/* 检查值的代码*/

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);
        }
    }
}

/按钮背景代码/

import java.awt.*;
import javax.swing.*;

public class ButtonBackground extends JFrame
{
    public ButtonBackground(String x)
    {
        setLayout( new FlowLayout() );
        //JButton normal = new JButton(" ");
        // add(normal);
        if(x.equals("green")) {
            JButton test1 = new JButton(" ")
            {
                @Override
                public void paintComponent(Graphics g)
                {
                    g.setColor( Color.GREEN );
                    g.fillRect(0, 0, getSize().width, getSize().height);
                    super.paintComponent(g);
                }
            };
            test1.setContentAreaFilled(false);
            test1.setBackground(Color.GREEN);
            add(test1);
        }
        else
        {
        JButton test1 = new JButton(" ")
            {
                @Override
                public void paintComponent(Graphics g)
                {
                    g.setColor( Color.RED );
                    g.fillRect(0, 0, getSize().width, getSize().height);
                    super.paintComponent(g);
                }
            };
            test1.setContentAreaFilled(false);
            test1.setBackground(Color.RED);
            add(test1);
        }
    }
}

最佳答案

据我所知,它已经发生了,但你正在捕捉它。建议您尽量避免使用 Pokémon 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.

关于java关于处理字符异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535519/

相关文章:

java - 如何利用redis提供的数据ID快速查询Oracle中的数据

java - Bamboo 制品部分遗失

java - 规模不断增长超出数学上下文精度

java - 改变 XYPlot 系列点的形状

java - (初学者 Java)Java 中的 Python time.sleep() 等价物?谷歌说 Thread.sleep() 用于多线程的东西,但尝试抛出错误

java - 如何杀死 CompletableFuture 相关线程?

java - 为什么 Display.asyncExec 或 Display.asyncExec 的 Object#wait 不是 "reasonable opportunity"?

java - 使用 JNI 将图像从 C++ 发送到 Java

java - SWT 从 Composite 中移除边距

java - 使用菱形运算符创建通用数组