简体   繁体   English

限制用户仅输入数字(int,float,double)

[英]Restrict user to input only numbers(int, float, double)

A user has to input only numbers(int, float, double) into an ArrayList. 用户只需输入数字(int,float,double)到ArrayList中即可。 If a user inputs anything but numbers, an exception InputMismatchException must be thrown. 如果用户输入数字以外的任何内容,则必须引发InputMismatchException异常。

I thought of using Number class. 我想到了使用Number类。

Scanner input = new Scanner(System.in);
ArrayList<Number> number = new ArrayList<Number>();
System.out.println("Enter number");
(data_type???) number_var = input.??????;
number.add(number_var);

This code will be in do while asking user if he/she wants to continue to give input or not. 在询问用户是否要继续输入时,将使用此代码。 The only problem is how to restrict user to give input as only numbers. 唯一的问题是如何限制用户仅以数字形式输入。 This should be done without creating another class but a method is allowed to restrict user. 应该在不创建另一个类的情况下完成此操作,但是可以使用一种方法来限制用户。

You could just accept all numbers as doubles. 您可以接受所有数字作为双精度数。 Ints and floats could be converted to doulbles seemlesly: 整数和浮点数似乎可以转换为双精度数:

Scanner input = new Scanner(System.in);
List<Double> number = new ArrayList<Double>();
System.out.println("Enter number");
number.add(input.nextDouble());

The docs for Scanner should describe what you need. Scanner的文档应描述您的需求。 Your scanner can read input as any kind of number that you want. 扫描仪可以将输入读取为所需的任何数字。 If the input doesn't match what you are expecting it will throw the InputMismatchException. 如果输入与您期望的不匹配,它将抛出InputMismatchException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM