-1

A program that I write recives an input like this

W 12.1 -1 2.2
B 1.2 3.2 1

And I need to check if the numbers are within coonstraints, so my idea is to store those numbers in array as integers. The numbers needs to be separated by the white spaces and the dots. Currently I have this code:

public static void main(String[] args) {
    Scanner reader = new Scanner (System.in);
    String input = reader.nextLine();
    String[] numbers = input.substring(2,input.length()).split("\\.");
    System.out.println(Arrays.toString(numbers));
        }

For input W 12.1 -1 2.2 the output is [12, 1 -1 2, 2] As you see I managed to make it deal with the dots but I can't remove the white spaces. What is the most resource efficient way to achieve my task ?

Tom
  • 3
  • 1
  • Use .split() and return array from index 1 to length of the array-1 – bigbounty Jul 23 '17 at 14:39
  • Split on the delimiter (whitespace, `split("\\s")`) and then process each element and check whether it is a number. You can do so **manually** or with a simple **regex match** like `-?\\d+\\.?\\d+` or by trying to parse it with `Integer#parseInt`, `Double#parseDouble` and so on. Also see: [How to extract numbers from a string and get an array of ints?](https://stackoverflow.com/questions/2367381/how-to-extract-numbers-from-a-string-and-get-an-array-of-ints) – Zabuzard Jul 23 '17 at 14:42

1 Answers1

-1

The numbers needs to be separated by the white spaces and the dots.

Apply replaceAll("\\s", ".") to replace whitespaces by ..

String[] numbers = input.replaceAll("\\s", ".").substring(2,input.length()).split("\\.");

or use another regex in split() that accepts both . and whitespace char :

String[] numbers = input.substring(2,input.length()).split("\\.|\\s");
davidxxx
  • 125,838
  • 23
  • 214
  • 215