Can i extract no. 2 digits from a string to an integer?

In my case, users can enter

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.

Any string method can extract the next digit from a string in Int format?

However, some errors still exist for my method. For example, he can exit the program for QQ or qq or q + any letters

Can best practices be provided?

Edit

e.g. p 0 1 char1 = str.charAt (0); // get p now i want to get 0 and 1 and save to int

+5
source share
2 answers

You can use capture groups (...) in your regular expression to extract pieces of 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 } 
+2
source

I would split into spaces.

 String input = "j 0 1"; String[] parts = input.split(" "); String command = parts[0]; int arg1 = Integer.parseInt(parts[1]); int arg2 = Integer.parseInt(parts[2]); 
0
source

Source: https://habr.com/ru/post/1260252/


All Articles