+ 1
How to stop user from entering numbers like 1.2.3 in Java
Number as user input in java
4 Respostas
+ 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.