java - 如果未输入有效整数,如何让程序因错误而终止?

标签 java dialog

对于学校,我正在编写一个程序,用户输入三个整数,程序找到这三个整数的乘积并将结果输出给用户。老师要求我使用JOptionPane类。当输入无效整数时,如何使程序因错误而终止。另外,如何在 java 窗口中输出答案?提前致谢!

import javax.swing.JOptionPane;

public class ASTheProductofThreeGUI {

    public static void main(String[] args) {

        //initializes variable "answer" of type integer

        //prompts the user to enter their first integer for the product of three
        int value1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first"
                + " value as an integer")); 

        //prompts the user to enter their second integer
        int value2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second"
                + " value as an integer")); 

        //prompts the user to enter their third integer
        int value3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third"
                + " value as an integer")); 

        int answer = value1 * value2 * value3; 

最佳答案

如果字符串不是有效的 Integer,Integer.parseInt 将引发异常。您应该处理 NumberFormatException,然后调用 System.exit。

import javax.swing.JOptionPane;

public class ASTheProductofThreeGUI {

public static void main(String[] args) {

    //initializes variable "answer" of type integer

    //prompts the user to enter their first integer for the product of three
try {
    int value1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first"
            + " value as an integer")); 

    //prompts the user to enter their second integer
    int value2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second"
            + " value as an integer")); 

    //prompts the user to enter their third integer
    int value3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third"
            + " value as an integer")); 
 catch (NumberFormatException e){
    e.printStackTrace("Invalid Integer entered.");
    System.exit(0);
 }
    int answer = value1 * value2 * value3; 

另外,询问家庭作业是一个令人不悦的问题,所以我将把你的第二个问题留给你来找出答案。

关于java - 如果未输入有效整数,如何让程序因错误而终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32893781/

相关文章:

java - Android:在 DialogFragment 中访问 SharedPreferences

validation - 如何仅在成功提交表单后显示对话框

java - DbUnit:NoSuchColumnException 和区分大小写

c - Windows 10 对话框标题栏行为

wpf - 配置为以编程方式执行更新的 ClickOnce 应用程序有时仍会显示 ClickOnce 更新可用提示

java - 通过 systemd 运行 Java 时无法识别的选项

android - 打开 Whatsapp 之类的对话框时显示动画?

java - 什么是构造函数链以及它在 Java 中是如何实现的?

java - 扩展 API 内部错误 : org. powermock.api.extension.reporter.MockingFrameworkReporterFactoryImpl

Java : Cannot send a form with Angular 5 that contain an input of type file to a REST backend (Spring Boot)