English 中文(简体)
如何检查无效用户的投入?
原标题:How do you check for invalid user input?

我正在起草一个方案,以检查用户的年龄,然后在答复时向他们提供反馈。 然而,我无法发现,如果用户输入的信息不是惯用,如何向用户发出错误的信息。 我如何能够围绕这一点开展工作?

import javax.swing.JOptionPane;

public class ifStatements {

    public static void main(String[] args) {
        while (1 == 1) {
            int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your Age: "));

            if (age >= 75) {
                JOptionPane.showMessageDialog(null, "You are old!");
                break;
            } else if (age >= 18) {
                JOptionPane.showMessageDialog(null, "You are an adult!");
                break;
            } else if (age > 0) {
                JOptionPane.showMessageDialog(null, "You are not an adult!");
                break;
            } else if (age <= 0) {
                JOptionPane.showMessageDialog(null, "Invalid response!");
            }
        }
    }
}

当用户投入任何价值而非分类时,即为错误信息。 在这一具体情况下,I类“w”。 我想能够发现所有类型的数据。 也许超高技能,但我想学习如何处理所有例外,即便是这个小型方案所花东西。

Exception in thread "main" java.lang.NumberFormatException: For input string: "w"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:665)
    at java.base/java.lang.Integer.parseInt(Integer.java:781)
    at ifStatements.main(ifStatements.java:16)
问题回答

喜欢这样做。 仅仅重新提出不准确的意见。 Java公约规定,类别名称应从上层开始。

public class IfStatements {
    public static void main(String[] args) {
        int age = 0;
        while (age <= 0) {
            try {
                age = Integer.parseInt(
                        JOptionPane.showInputDialog("Enter your Age: "));
            } catch (NumberFormatException nfe) {
                displayError();
                continue;
            }
            if (age >= 75) {
                JOptionPane.showMessageDialog(null, "You are old!");
                break;
            } else if (age >= 18) {
                JOptionPane.showMessageDialog(null, "You are an adult!");
                break;
            } else if (age > 0) {
                JOptionPane.showMessageDialog(null, "You are not an adult!");
                break;
            }
            // must be <= 0 here so just display the message.
            displayError();
            
        }
    }
    private static void displayError() {
        JOptionPane.showMessageDialog(null,
                "Please enter a number > 0", "Invalid Input",
                JOptionPane.ERROR_MESSAGE);
    }
}

<<https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)"rel=“nofollow noreferer”>Integer.parseInt > <

您可使用try-liver>,以捕获被推翻的例外情况。

The syntax is as follows.

try {

} catch (ExceptionType name) {

}

try-block 栏内发言时,该栏目已卸下,并登录在fish>。

可通过 副渔获物/em>-block上公布的名称查阅Exception

这里是贵国法典的一个实例,利用try- submissions验证输入值。

int age;
while (1 == 1) {
    try {
        age = Integer.parseInt(JOptionPane.showInputDialog("Enter your Age: "));
        if (age >= 75) {
            JOptionPane.showMessageDialog(null, "You are old!");
            break;
        } else if (age >= 18) {
            JOptionPane.showMessageDialog(null, "You are an adult!");
            break;
        } else if (age > 0) {
            JOptionPane.showMessageDialog(null, "You are not an adult!");
            break;
        } else if (age <= 0) {
            JOptionPane.showMessageDialog(null, "Invalid response!");
        }
    } catch (NumberFormatException exception) {
        JOptionPane.showMessageDialog(null, "Invalid age");
    }
}

下面是基本示范,根据您的法典改编,该守则使用除外>通过无效><>>>>>> /em> 输入。

The age method will attempt to parse the value returned by JOptionPane#showInputDialog.
If it is successful it will return the value, otherwise, if an exception is thrown, it s caught and a new IllegalArgumentException exception is thrown, with the input value as the message.

public static void main(String[] args) {
    int age;
    boolean exit;
    do {
        exit = true;
        try {
            age = age();
            if (age >= 75) message("You are old!");
            else if (age >= 18) message("You are an adult!");
            else if (age > 0) message("You are not an adult!");
            else {
                message("Invalid response!");
                exit = false;
            }
        } catch (IllegalArgumentException exception) {
            String string = exception.getMessage();
            if (string != null) {
                if (string.isBlank()) message("Input required");
                else message("Invalid age,  %s ".formatted(exception.getMessage()));
                exit = false;
            }
        }
    } while (!exit);
}

static int age() throws IllegalArgumentException {
    String string = null;
    try {
        string = JOptionPane.showInputDialog("Enter your Age: ");
        return Integer.parseInt(string);
    } catch (NumberFormatException exception) {
        throw new IllegalArgumentException(string);
    }
}

static void message(String string) {
    JOptionPane.showMessageDialog(null, string);
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...