In my case ,the users can input
f 0 ,f 1, f 2//1 digit
p 0, p 1 ,p 2//1 digit
j 0 1, j 0 2, j 1 0....(any combination of 0,1,2) //2 digits
q ,Q //for quit
I use
str = scanner.nextLine();//get the whole line of input
if(str.matches("[fpjq]\\s[012]"))......//check vaild input
char1=str .charAt(0);//get the first letter
Then I want to get the next digit now .
Any string method can extract the next digit from string into Int format?
However ,some bugs still exist for my method . For example , it can quit the program for QQ or qq or q+any letters
Any better methods can be provided?
for example p 0 1
char1=str .charAt(0);//get p
now I want to get 0 and 1 and store into int
You can use capturing groups (...)
in your regex to extract parts of the matched data:
str = scanner.nextLine();
Pattern regex = Pattern.compile("^([fpjq])(?:\\s+([012]))?(?:\\s+([012]))?$");
Matcher matcher = regex.matcher(str.trim());
if (matcher.find()) {
String letter = matcher.group(1);
String digit1 = matcher.group(2); // null if none
String digit2 = matcher.group(3); // null if none
// use Integer.parseInt to convert to int...
} else {
// invalid input
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With