R
R
Roman Deniskin2021-08-28 14:22:16
Java
Roman Deniskin, 2021-08-28 14:22:16

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

1 answer(s)
M
Mimocodil, 2021-08-28
@romka123

Variable type is checked through instanceof

Object r = 13.1;
if (r instanceof Double) {
    System.out.println("matches double");
}

You can recognize a string as a double, for example, using a regular expression
String example = "1331.2";
if (Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,][0-9]+$", (CharSequence) example)) {
    System.out.println("matches double");
}

You can find some library, you can write a method yourself that iterates over the string character by character. Or you can just use Double.parseDouble() , it's not that cumbersome.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question