【问题标题】:How to validate for a non-integer being entered in an integer data type? [duplicate]如何验证在整数数据类型中输入的非整数? [复制]
【发布时间】:2020-01-21 21:40:36
【问题描述】:

我必须创建一个商店来购买商品。选择商品后,我会提示用户输入他们想要购买的商品的数量。

// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();

如果用户输入一个非整数(即十进制,字符...),它会破坏程序。 有没有办法验证这个非整数输入?

谢谢

【问题讨论】:

  • 我推荐阅读:Lesson: Exceptions
  • nextInt() 在从数据流中读取数据时,浮点数、字节数等都很棒,但人类输入的用户输入却非常难以预测。您通常必须将所有内容都读取为 Strings,然后验证该字符串是否代表您想要的内容。
  • @StephenP 一般来说,我同意你的观点,但即使在数据流的情况下,我也建议采用字符串值,然后尝试将其转换为预期的类型。信任他人代码的伤痕很长很深。
  • 在尝试调用nextInt之前使用hasNextInt()
  • @hooknc 同意了。事实上,我从未使用过java.util.Scanner

标签: java validation


【解决方案1】:

当然,接受 String 值而不是 int,检查是否可以将该 String 值解析为 int,如果可以,那么就这样做。如果不是,则发送一条消息,说明输入的值必须是数字。

这可以在一个while循环中完成。

import java.util.Scanner;

public class ScannerInputInt {

    public static void main(String... args) {

        Scanner in = new Scanner(System.in);

        Integer input = null;

        do {

            System.out.println("Please enter number: ");

            String s = in.nextLine();

            try {

                input = Integer.parseInt(s);

            } catch (NumberFormatException e) {

                System.out.println("ERROR: " + s + " is not a number.");
            }

        } while (input == null);
    }
}

【讨论】:

  • "检查是否可以将该 String 值转换为 int" 这是永远做不到的。调用Integer.parseInt 不是castinginput = (Integer) s; 将是 casting
  • @Andreas 很公平。改变了措辞...
【解决方案2】:

如果您不想使用 Exceptions 方法。你可以试试这个。

这段代码将继续询问用户输入,直到用户输入正确的输入。

System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
   input.nextLine(); // Discarding the line with wrong input
   System.out.print("Please Enter correct input: "); // Asking user again
   isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();

输出:

Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2

我认为这是更好的方法,因为我认为使用异常控制程序的流程是不好的做法,当有其他可以使用的东西时应该避免。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多