如何检查用户输入是否为整数?

时间:2014-10-01 21:33:21

标签: java java.util.scanner

我正在编写单类/单方法程序,我要求用户输入整数,双精度或字符串(除了int或double之外的任何东西都是字符串)。我知道我需要使用什么,但是我无法理解它是如何适合我的程序的。

我不确定如何使用hasNext方法来确定它是什么类型的输入。我正在研究整数案例;如果用户全部用空格分隔,如何检查用户输入的每个值?一旦我知道它是一个整数,我将如何使用下一个方法将数据读入单个变量,以便我可以对它们执行简单的算术运算?感谢帮助!

这是我到目前为止所拥有的:

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();
   }
}

2 个答案:

答案 0 :(得分:0)

如果您知道分隔符,可以使用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);
}

编辑,取两个:现在应该没有错误......

答案 1 :(得分:0)

首先,我建议您始终将用户信息作为字符串获取,例如,使用:

String input = scanner.nextLine();

查看它们是否被空格分隔(// s是一个或多个空格的正则表达式):

String[] splits = input.split("\\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()