1

I want to create a Java program where a user will input something and the output will show what type of data the input is..? For example:

Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.

Please help as I am clueless on how to work this out

Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
IVAN PAUL
  • 157
  • 1
  • 3
  • 15

3 Answers3

1

A simple approach could go like this; starting with some input string X.

  1. If X can be parsed as Integer --> it is an int/Integer
  2. Then you try Long
  3. Then Float
  4. Then Double
  5. If nothing worked, you probably have a string there

( with "parsing" I mean using methods such as Integer.parseInt() ... you pass in X; and when that method doesn't throw an exception on you, you know that X is an Integer/int )

But: such a detection very much depends on your definition of valid inputs; and potential mappings. As there zillions of ways of interpreting a string. It might not be a number; but given a correct format string ... it could be timestamp.

So the very first step: clarify your requirements! Understand the potential input formats you have to support; then think about their "mapping"; and a potential check to identify that type.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

You can get a string and try to parse it as other types:

Scanner s = new Scanner(System.in);//allows user input
input = s.nextLine();//reads user input
try{//java will try to execute the code but will go to the catch block if there's an exception.
    int inputInt = Integer.parseInt(input);//try to convert input to int
catch(Exception e){
    e.printStackTrace();//this tell you exactly what went wrong. If you get here, then the input isn't an integer.
}
//same with double
ItamarG3
  • 4,092
  • 6
  • 31
  • 44
1

This should work for your purpose:

import java.util.Scanner;

public class DataType 
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      if(in.hasNextByte(2))
         System.out.println("Byte");
      else if(in.hasNextInt())
         System.out.println("Integer");
      else if(in.hasNextFloat())
         System.out.println("Float");
      else if(in.hasNextBoolean())
         System.out.println("Boolean");
      else if(in.hasNext())
         System.out.println("String");
   }
}

Note that the order of if...else statements is very important here because of the following set relations with respect to patterns:

  1. All byte patterns can be integers
  2. All integer patterns can be floats
  3. All float patterns can be Strings
  4. All booleans can be Strings

There are quite a lot of hasNext..() methods in the Scanner class, such as BigInteger, short, and so on. You may refer the Scanner class documentation for further details.

Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97