Issue
I am making a program that detects the input data type t whether it's integer or double . I have don't the following code so far. But I don't know how to store the data I input.
Code:
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.");
}
}
}
Solution
If you use the apache commons lib you can use StringUtils and NumberUtils. In general define a variable for the scanner input and validate its content, validating the input directly is more restrictive.
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);
}
}
You can store the input in a variable like in the above example.
String myInput = scanner.nextLine();
Answered By - Felix Schildmann