2016-08-12 125 views
-4

我想知道如何檢查java中的輸入類型?java中的輸入類型檢查

  • 如果我輸入23它應該說「輸入是整數類型」
  • 如果3.0然後「輸入爲浮子式」
  • 如果蘇曼氏然後「的輸入是字符串類型」等
+0

你的問題是什麼? – David

+3

http://stackoverflow.com/questions/5333110/checking-input-type-how –

+0

你必須bruteforce它: – Javant

回答

0

使用正則表達式模式和內置的模式類:

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