Answer the question
In order to leave comments, you need to log in
How to check data type in Java via if?
Hello. I'm currently relearning from PHP to Java and had a question that I couldn't find a simple answer to. Already several times, in the course of programming, I am faced with the fact that I need to organize some kind of check. Here I sketched
a small program in which I check through the
construction of exceptions whether the input string is a double type or not: the check would take one line:
if (!is_double($cmd)) {
echo "Data type must be floating point");
}
In my opinion, this is much more concise and understandable. What am I doing wrong? Is Java always this cumbersome, or are there ways to solve this kind of problem more concisely, through if constructs? Please do not throw slippers at me, I just started learning Java, although in PHP I already have decent experience. Perhaps I don’t know about some kind of framework that allows you to solve such problems more quickly and beautifully, or the very methodology of the Java language is such that most of the checks are done through exceptions ...
Answer the question
In order to leave comments, you need to log in
Variable type is checked through instanceof
Object r = 13.1;
if (r instanceof Double) {
System.out.println("matches double");
}
String example = "1331.2";
if (Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,][0-9]+$", (CharSequence) example)) {
System.out.println("matches double");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question