-1

My method checks a user input if it is an integer. If it is, it prints a certain something in my code, if it is not an integer, it prints Invalid input. It works good except for when i input any integer ending with the letter "d", it accepts it as an integer. How do I fix this? Here's my code so far.

static boolean isNumber(String text) {
    try {
        Double.parseDouble(text);
        return true;
    } catch (NumberFormatException e) {
        System.out.println("Input is non-numerical or incorrect.");
        return false;
    }
}

do {
     System.out.print("Input loan principal amount : ");
     input = s.nextLine();
} while (!isNumber(input));
     double loan = Double.parseDouble(input);
MOnkey
  • 751
  • 6
  • 13
JavaNewbie
  • 57
  • 6
  • 3
    why you parse double when you need an integer? do `Integer.parseInt()` instead – Stranger in the Q Feb 22 '20 at 08:55
  • 2
    Does this answer your question? [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – BitNinja Feb 22 '20 at 08:55

2 Answers2

2

According to Java Language Specification, floating point types can have suffixes (shortent version):

FloatingPointLiteral:
    DecimalFloatingPointLiteral
    HexadecimalFloatingPointLiteral

DecimalFloatingPointLiteral:
    Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt
    . Digits ExponentPartopt FloatTypeSuffixopt
    Digits ExponentPart FloatTypeSuffixopt
    Digits ExponentPartopt FloatTypeSuffix

...

FloatTypeSuffix: one of
    f F d D

If you already using java.util.Scanner, you can use nextDouble() or nextBigDecimal() (which is better if your program is going to deal with money values like in your case).

rkosegi
  • 14,165
  • 5
  • 50
  • 83
  • It would be better to point to the documentation of [`Double.parseDouble`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Double.html#parseDouble(java.lang.String))/[`Double.valueOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Double.html#valueOf(java.lang.String)) as that is the formal definition of its behaviour. – Mark Rotteveel Feb 22 '20 at 11:30
0

This question is a typical homework question for beginners.

Your teacher does not want you to find shortcuts and use existing functions that will give you the answer in one line, but to create a loop and check every character in the string one by one.

Like this:

for (char c : text.getChars()) {
    //code that checks if c is a digit character and exits if it is not
}

return true;

Remember that trying to use existing functions like parseDouble or parseInt will fail for very long numbers that should still be valid!

Lev M.
  • 6,088
  • 1
  • 10
  • 23