java 爪哇。当 userInput 是字符串而不是 int 时,如何生成错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25700196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:29:18  来源:igfitidea点击:

Java. How to make an error message for when userInput is a string instead of an int?

javauser-input

提问by Mikaela

I'm working on a sort of test in Java, in which the user is given a question like this: " 4 + ? = 12". The numbers are randomised and so is the questionsmark.

我正在用 Java 进行某种测试,其中向用户提出这样的问题:“4 + ? = 12”。数字是随机的,问号也是。

I need to make an error message for when the user input isn't an int. For example if the user types in the word "eight" instead of "8" an error message will show up. How can I do this?

当用户输入不是 int 时,我需要发出错误消息。例如,如果用户输入单词“8”而不是“8”,则会显示错误消息。我怎样才能做到这一点?

回答by ortis

    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();//get the next input line
    scanner.close();
    Integer value = null;
    try
    {
        value = Integer.valueOf(input); //if value cannot be parsed, a NumberFormatException will be thrown
    }
    catch (final NumberFormatException e)
    {
        System.out.println("Please enter an integer");
    }


    if(value != null)//check if value has been parsed or not
    {
        //do something with the integer

    }

回答by ErstwhileIII

Consider the following code that both ensures that an integer is provided, and prompts the user to enter the correct type of input. You could extend the class to handle other restrictions (min/max values, etc.)

考虑以下代码,它既确保提供一个整数,又提示用户输入正确的输入类型。您可以扩展该类以处理其他限制(最小值/最大值等)

TestInput Class

测试输入类

package com.example.input;
import java.util.Scanner;
public class TestInput {
    public static void main(String[] args) {
        int n;
        Scanner myScanner = new Scanner(System.in);

        n = Interact.getInt(myScanner,"Enter value for ?", "An integer is required");
        System.out.println("Resulting input = " + n);
    }
}

Interact Class

互动课

package com.example.input;
import java.util.Scanner;
public class Interact {

    public static int getInt(Scanner scanner, String promptMessage,
            String errorMessage) {
        int result = 0;

        System.out.println(promptMessage);
        boolean needInput = true;
        while (needInput) {
            String line = scanner.nextLine();
            try {
                result = Integer.parseInt(line);
                needInput = false;
            } catch (Exception e) {
                System.out.println(errorMessage);
            }
        }
        return result;
    }
}

回答by msrd0

First of all, you need to get the String the user typed for the '?' in the question. If you do it simply with System.inand System.out, you would do it like this:

首先,您需要获取用户为“?”键入的字符串。在问题中。如果你只是用System.inandSystem.out来做,你会这样做:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();

If you thought of an easy version with GUI, you could use JOptionPanelike this:

如果你想到了一个带有 GUI 的简单版本,你可以这样使用JOptionPane

String line = JOptionPane.showInputDialog("4 + ? = 12");

Else, if you have a real GUI, you could read the user's input from a JTextFieldor similar:

否则,如果你有一个真正的 GUI,你可以从一个JTextField或类似的地方读取用户的输入:

String line = textField.getText();

(In this case you could also use a JFormattedTextFieldthat filters the input for an Integer. This will make the check whether the input is an Integer or not unnecessary.)

(在这种情况下,您还可以使用JFormattedTextField过滤整数的输入。这将检查输入是否为整数。)



Now, you need to parse the String to an int:

现在,您需要将 String 解析为一个int

int value;
try
{
    value = Integer.parseInt(line);
}
catch (NumberFormatException nfe)
{
    // the user didn't enter an Integer
}
doSomethingWith(value);

The content of the catch-block differs from the variant you took above. If you took the first one with System.inand System.out, you could write something like this:

catch-block的内容与您上面采用的变体不同。如果你用System.inand取第一个System.out,你可以这样写:

System.out.println("Your input is not an Integer! Please try again");

If you took the version with JOptionPane, you could write something like this:

如果您使用 版本JOptionPane,您可以编写如下内容:

JOptionPane.showMessageDialog(null, "Your input is not an Integer! Please try again");

Else, you need to have a JLabelfor that witch has initially no content. Now, set it for 3 seconds to the text:

否则,您需要JLabel为那个女巫最初没有内容。现在,将其设置为 3 秒的文本:

errorLabel.setText("Your input is not an Integer! Please try again");
new Thread(() ->
{
    try { Thread.sleep(3000); } // sleep 3 sec
    catch (InterruptedException ie) {} // unable to sleep 3 sec
    errorLabel.setText("");
}).start();

Note that the last version is also compatible with the second one.

请注意,最后一个版本也与第二个版本兼容。

Now, you should either generate a new question, or repeat the read/parse procedure until the user entered an Integer.

现在,您应该生成一个新问题,或者重复读取/解析过程,直到用户输入一个整数。