+ 1
How to stop user from entering numbers like 1.2.3 in Java
Number as user input in java
4 RĂ©ponses
+ 2
parseFloat()
+ 2
Kind of unclear on what you want, but if you want to prevent a user from inputting a string that contains only digits or decimals, you can check that string using a return boolean check method:
boolean isDigits(String input){
String regex = â[0-9, .]+â;
return input.matches(regex);
}
and basically this will return false if the input parameter does NOT contain only digits or decimals or true if the input parameter DOES contain only digits or decimals and then you can tie that to a loop to prompt user to continue retrying their input until that isDigits returns false. For example:
Scanner scan = new Scanner(System.in);
System.out.println(âEnter textâ);
String text = scan.nextLine();
if(isDigits(text) == true) {
do {
System.out.println(text + â is only digits and/or decimals. Try again: â)
text = scan.nextLine();
} while(isDigits(text) == true);
}
System.out.println(text + â is not only digits and/or decimals!â);
This will prevent user from inputting ONLY digits or decimals, however they will still be able to input a combination of letters and digits IE: â1.2.3â == true and âabc123â = false
now if you want to allow ONLY the alphabet (abcde and so on) you would re-write this as:
boolean isLetters(String input){
String regex = â[a-zA-Z]+â;
return input.matches(regex);
}
if(isLetters(text) == false) {
do {
System.out.println(text + â is not allowed. Only Letters. Try again: â)
text = scan.nextLine();
} while(isLetters(text) == false);
}
System.out.println(text + â is allowed!â);
this will not accept anything other than letters a-z (lower and upper case)
Iâm positive there are better ways to do it but I am rather new to this myself and found this to work for me in most cases!
+ 1
convert the number to string. find the index of the first decimal. reverse the string. find the index of decimal on this str. if the indices don't match there are more than one decimal. throw an Error
+ 1
There are many ways to solve thIs. The easiest will be to parse the input to float or double and throw/catch the exception if an invalid input is entered.