如何存储我输入的数据并在 Java 中检测到它的数据类型?

How do store the data i have input and detected it's data type in Java?

我正在编写一个程序来检测输入数据类型 t 是 integer 还是 double 。到目前为止,我还没有以下代码。但是我不知道如何存储我输入的数据。

代码:

import java.io.*;
import java.util.Scanner;

public class HeightCalc {
    public static int temp,result;
    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);

        if (input.hasNextInt()) {
            System.out.println("Integer.");
        }

        else if (input.hasNextFloat() || input.hasNextDouble()) {
            System.out.println("Double.");
        }
    }
}

如果您使用 apache 公共库,则可以使用 StringUtils 和 NumberUtils。 通常为扫描仪输入定义一个变量并验证其内容,直接验证输入更具限制性。

import java.io.*;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math;

public class HeightCalc {
    public static int temp,result;
    public static void main(String[] args) {

        Scanner scanner = new Scanner (System.in);
        String input = scanner.nextLine();

  if (StringUtils.isNumeric(input))
  {
     System.out.println("Integer.");
  }

  else if (NumberUtils.isCreatable(input))
  {
      System.out.println("Double.");
  }

 System.out.println("Input:" + input);
}
}

您可以像上例一样将输入存储在变量中。

String myInput = scanner.nextLine();

如果我做对了,您需要将输入的数字值存储到一个变量中吗?

我将创建 Number inputValue 变量并将扫描器的值存储到其中。

        Number inputValue;

        Scanner input = new Scanner (System.in);

        if (input.hasNextInt())
        {
            inputValue = input.nextInt();
            System.out.println("int.");
        }  else if (input.hasNextFloat() || input.hasNextDouble())
        {
            inputValue = input.nextDouble();
            System.out.println("Double.");
        }

inputValue 将从 .nextInt()nextDouble().

继承 class

但是我会考虑将输入存储到一个变量中以摆脱这种情况并从中导出其他数字 classes。

整数示例

inputValue = input.nextDouble();

public int getIntValue(){
   return inputValue.intValue();
}