【问题标题】:Input type checking in javajava中的输入类型检查
【发布时间】:2016-08-12 16:05:29
【问题描述】:

我想知道如何在 java 中检查输入类型?

  • 如果我输入 23 它应该说“输入是整数类型”
  • 如果是 3.0 则“输入为浮点型”
  • 如果 Suman 则“输入为字符串类型”等。

【问题讨论】:

标签: java


【解决方案1】:

使用 regex 模式 和内置 Pattern 类:

import java.util.Scanner;
import java.util.regex.Pattern;

public class TestClass {

    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        boolean containsDigit = Pattern.compile("[0-9]").matcher(input).find();
        boolean containsNonDigitNonPeriod = 
            Pattern.compile("[!--/:-~]").matcher(input).find();
        int numberOfPeriods = input.replaceAll("[^.]", "").length();

        if (containsDigit && !containsNonDigitNonPeriod)
        {
            if (numberOfPeriods > 1)
                System.out.println("A string has been input.");
            else if (numberOfPeriods == 1)
                System.out.println("A float has been input.");
            else 
                System.out.println("An integer has been input.");
        }
        else 
            System.out.println("A string has been input.");

        scanner.close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2015-09-04
    • 2013-11-16
    • 1970-01-01
    • 2011-07-17
    • 2014-06-08
    相关资源
    最近更新 更多