Let {1, 2, 3, 4} be entered into the console, and I don’t know the number of numbers, I want to work with it as an array of integers, but it’s clear that I can’t consider it as an array of integers, since there are commas and quotes, I wanted to try to treat it as a string, but after the space, the reading stops.

  • So what do you want to be in the string when entering "{1, 2, 3, 4}"? Or do you want to parse the entered line just into an array of numbers? - alex-rudenkiy
  • First save it to string, and then convert to an array of numbers - Gymon

2 answers 2

If I understood correctly, it should turn out like this ...

import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.*; public class MyApp { static List<Integer> mynumbers = new ArrayList<Integer>(); public static void main(String[] args) { String input = "{1, 2, 3, 4}"; Pattern pattern = Pattern.compile("\\d"); Matcher matcher = pattern.matcher(input); while(matcher.find()) mynumbers.add(Integer.parseInt(matcher.group())); } } 
  • Unfortunately, your solution does not work correctly on the following input: "{11, 12, 23, 34}". But it seems to become correct with this pattern: "[\\ d] +" - velial
  • The fact is that it is not possible to treat this as a string right away, since there are spaces there, which is perceived as the end of the input string. - Gymon
  String input = "{1', 2; 3, 4, 5 6, 7}"; Scanner scanner = new Scanner(new StringReader(input.replaceAll("[^\\d]+", " "))); while (scanner.hasNextInt()) { System.out.println(scanner.nextInt()); } 

Output:

 1 2 3 4 5 6 7