r/javahelp • u/THE_BARNYARD_DOG • Jul 06 '20
Homework Not sure how to restrict user input to the correct data type
Hi so I’m pretty new to coding I’m working through a 101 level java coding class but I’ve come to an assignment where I need to write a few input methods that get input from the user of certain data types and reject input that is not the correct data type. I found some code online that was supposed to work for strings and it sort of works but it only accepts 1 character not whole words or phrases, here’s what I have so far
public static String getString() { String userString; System.out.println(“Please enter a few words”); while(!keyboard.hasNext(“[A-Za-z+]”)){ System.out.println(“You did not enter any letters”) keyboard.nextLine(); } userString = keyboard.nextLine(); System.out.println(“You entered: “ + userString); return userString; }
So this code works for any non-alphabetical data such as numbers and symbols and rejects them and it works for single letters and accepts them but the problem I am having is that when I enter multiple letters at once such as “aaa” the code rejects the input and displays the error message I wrote. I found this code online and it said it would take any length string but for some reason it is not working for me. Also when I have to write the integer version of this method could I pretty much reuse the same code but with “[0-9+]” in my while statement instead of the “[A-Za-z+]”?
Edit: wow a spent a bunch of time formatting that code properly on my phone and reddit still shoved it all together wow.
6
4
u/gray_catbird Jul 07 '20
[A-Za-z+] matches only on a single character. I think you want [A-Za-z]+. Sites like regex101 or RegExr are very helpful to checking your regex expressions, by the way.
Alternatively, instead of a regex, you could try
instanceofto validate that the user's input is a String