r/javahelp • • 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.

17 Upvotes

5 comments sorted by

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 instanceof to validate that the user's input is a String

1

u/THE_BARNYARD_DOG Jul 07 '20

So I just need to move the + out of the brackets? And I’m pretty new to java but I’ll look into the regex and instanceof

3

u/__helix__ Jul 07 '20

Trick with posting code here is to give it one 'tab' indentation to the entire block.

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; 
}

1

u/gray_catbird Jul 07 '20

Correct. If it's outside the brackets, the + quantifies the preceding expression; if it's in the bracket, + is treated as a literal. Plug each one into regex101.com and you can test various strings against it to get a feel for how regex works.

6

u/Im_Mehed Jul 07 '20

Try putting your code in pastebin so we can read it and then linking it here.

https://pastebin.com/