Java 如何检查用户输入是否为整数?
我正在编写一个单类/单方法程序,并要求用户输入整数、双精度或字符串(除int或double以外的任何东西都是字符串)。我有一个想法,我需要使用什么,但我很难理解它如何适合我的程序 我不知道如何使用hasNext方法来确定它是什么类型的输入。我现在正在处理integer案例;如果用户输入的每个值都用空格隔开,我如何检查它们?一旦我知道它是一个整数,我将如何使用下一个方法将数据读入单个变量,以便对它们执行简单的算术?谢谢你的帮助 以下是我目前掌握的情况:Java 如何检查用户输入是否为整数?,java,java.util.scanner,Java,Java.util.scanner,我正在编写一个单类/单方法程序,并要求用户输入整数、双精度或字符串(除int或double以外的任何东西都是字符串)。我有一个想法,我需要使用什么,但我很难理解它如何适合我的程序 我不知道如何使用hasNext方法来确定它是什么类型的输入。我现在正在处理integer案例;如果用户输入的每个值都用空格隔开,我如何检查它们?一旦我知道它是一个整数,我将如何使用下一个方法将数据读入单个变量,以便对它们执行简单的算术?谢谢你的帮助 以下是我目前掌握的情况: import java.util.Scann
import java.util.Scanner;
public class InputParser
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse: ");
int numValues = scanner.nextInt();
System.out.println("Please enter " + numValues + " values: ");
String userInput = scanner.nextLine();
}
}
如果知道分隔符,可以使用
String.split()
分隔用户输入:
String userInput = scanner.nextLine();
String[] separated = userInput.split(" "); // use " +" for delimiter if input like "3 2 2 4" should be allowed
for (String singleInput : separated) {
// proceed the single input here
}
编辑:假设您已经有了进行整数/双精度/字符串输入的方法:
void proceedInt(int number) {
...
}
void proceedDouble(double number) {
...
}
void proceedString(String text) {
...
}
然后在上述for循环中区分输入类型,如下所示:
for (String userInput : separated) {
try {
int number = Integer.parseInt(userInput);
proceedInt(number);
continue; // we proceed to the next element prematurely since no double or string anyway
} catch (NumberFormatException nfe) {
}
try {
double number = Double.parseDouble(userInput);
proceedDouble(number);
continue; // proceed to the next element prematurely or you will also treat the input as a string and proceed the input twice: as a double and as a string
} catch (NumberFormatException nfe) {
}
// if we landed here, we can say for sure that the input was neither integer nor double, so we treat it as a string
proceedString(userInput);
}
编辑,第二步:现在应该是无错误的…首先,我建议您始终以字符串形式获取用户信息,例如,使用:
String input = scanner.nextLine();
要查看它们是否由空格分隔(//s是一个或多个空格的正则表达式),请执行以下操作:
迭代找到的每个字符串:
for (String eachString: splits) {
//do what you need
}
要分析整数,请尝试以下操作:
try {
myint = Integer.parseInt(input);
} catch (NumberFormatException e) {
//Do what you need to do because input was NOT an int
}
与double相同,但改用:
Double.parseDouble()
谢谢,所以一旦我把它分开,我如何阅读每一个来判断它是否是一个整数?基本上,使用另一个答案中建议的解决方案。我现在就更新我的。
Double.parseDouble()