this is my Function to control the double input from the user but it control only integer values if the user enter a comma ‘,’ character like for example 100,300 it refuse to accept it so i’m thinking of doing the following : when the function encounter a comma character ‘,’ it will change it to a dot character ‘.’ and then i’m wondering if now the string value can be converted to a double like “100.300” `
public static double controlDoubleInput() { Scanner scanner = new Scanner(System.in).useDelimiter("n"); String option = scanner.next(); boolean isNotDigit = true; char[] array = option.toCharArray(); do { for(char c : array) { if(Character.isDigit(c)) { isNotDigit = false; } else { isNotDigit = true; break; } } if(isNotDigit) { System.out.println("input mismatch please retry : "); option = scanner.next(); array = option.toCharArray(); } } while(isNotDigit); return Double.parseDouble(option); }
`
Advertisement
Answer
Use localization.
try (Scanner scanner = new Scanner(System.in).useDelimiter("n")) { String option = scanner.next(); NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); while (true) { try { return nf.parse(option).doubleValue(); } catch (ParseException e) { System.out.println("input mismatch please retry : "); option = scanner.next(); } } }