1
\$\begingroup\$

I was getting a NoSuchElementException when parsing my double so I had to refine my code to validate the input. Is there anything you recommend?

The reason it was throwing a NoSuchElementException was due to new Scanner(extractFieldValue( inputValues, input)); not having a double in the next token so if the input does not contain a double in the next token then I want to skip it. If it does then proceed with the code.

Code prior to the validation:

public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {
    Scanner scan = new Scanner(extractFieldValue( inputValues, input));                
    String formatString = extractFieldValue( inputValues, format);            
    DecimalFormat formatter = new DecimalFormat(formatString);            
    return fillResult(formatter.format(number));
 }

Code after change that does validation on the input:

public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {
    Scanner scan = new Scanner(extractFieldValue( inputValues, input));
    double number = 0;
    if(scan.hasNextDouble()) {
        number = scan.nextDouble();
    }                
    String formatString = extractFieldValue( inputValues, format);            
    DecimalFormat formatter = new DecimalFormat(formatString);            
    return fillResult(formatter.format(number));
 }

extractFieldValue returns a String.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Could you clarify, with examples, what some valid and invalid inputs look like, and what you want to happen in each case? \$\endgroup\$ – 200_success Dec 29 '16 at 15:03
  • \$\begingroup\$ @200_success I have edit it \$\endgroup\$ – robben Dec 29 '16 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.