0

I want to create an error message if the user has entered multiple decimal point in the textfield.I can only check it if it has 1. but I dont know how if there are many.

  • There are lots of alternative approaches here [How do I count the number of occurrences of a char in a String?](https://stackoverflow.com/q/275944/2985643) and here [Simple way to count character occurrences in a string](https://stackoverflow.com/q/6100712/2985643). – skomisa Mar 22 '19 at 03:50

2 Answers2

1
String text = myTextField.getText();
String[] number = text.split("\\.");

This simple bit of code gives you all you need. The number of elements in the array - 1, is the number of times the char '.' appears in your input.

EDIT: In case the user might enter values which have several . chars after one another, example: "5.....", you need to use the overloaded version of the split method.

split(myRegex)

will retrieve the values between the matches, if there are any,

split(myRegex, -1)

will get them all, regardless of whether there is some value between the matches.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • Your code doesn't work with a String value of **"5....."**. You need to call the overloaded implementation of `split()` with a negative limit like this: `text.split("\\.", -1)` – skomisa Mar 22 '19 at 04:12
  • @skomisa true. I just didn't imagine someone who would want to enter a (somewhat) valid number would enter something like that. – Stultuske Mar 22 '19 at 06:46
1

Its not exactly what the question asks but would surely handle multiple dots and much more. The idea is to fetch the input as String from Textfield and then convert that string to double. If it throws an exception prompt user that the given input is invalid and ask to enter the value again. This would handle all your input data validation. Code would be something like this,

String inputNum = myTextField.getText();
double actualNum = 0.0;
try {
  actualNum = Double.parseDouble(inputNum);  
} catch (NumberFormatException ne){
    // Prompt User
}
  • the problem is, this will throw Exceptions in other cases as well. for instance: the value being too large. For all we know, the goal of the user is to filter out the first x decimal points (if there are x + 1) and keeping the last one, without having to re-enter the value. That too would be impossible – Stultuske Mar 21 '19 at 07:41