2

I have multiple line input where each line is line of matrix. I save this line as string and after that i want to split this string based on spaces, but due to better readability the number of spaces between number is not defined. So when i want to parse to int afterwards, it throws an error because, on some places there are more than one space. Is there any solution how i could fix that problem? Thanks

Here is my code, how i tried to solved that

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
int[][] matrix=new int[n][n];
String[] temp;
for (int row = 0; row < n; row++) {
    line =br.readLine();
    temp = line.split("\\s+");
    for(int i=0;i<n;i++){
    matrix[i][row]=Integer.parseInt(temp[i]);
}

here is examplary input

10 10  0 10  5
 5 20 10  7 12
 1  2  3  5  9
10 15 20 35  2
 2 15  5 15  2
preneond
  • 497
  • 2
  • 5
  • 21

3 Answers3

3

The issue is when you have spaces in the beginning of the String:

"10 10  0 10  5".split("\\s+"); // ["10", "10", "0", "10", "5"]
" 5 20 10  7 12".split("\\s+"); // ["", "5", "20", "10", "7", "12"]

So then you get an extra empty String. Adding an extra trim() should help:

line.trim().split("\\s+");
ericbn
  • 10,163
  • 3
  • 47
  • 55
1

Just replace multiple spaces with single spaces

see Java how to replace 2 or more spaces with single space in string and delete leading spaces only

And after that just do the splitting as you would normaly do.

Community
  • 1
  • 1
  • What @Aleksandar is saying is an easy way to go about it. Just replace multiple spaces with a single space using `trim()` and then do what you have done already. – amelogenin Feb 23 '16 at 18:56
-1

If you write the logic portion correctly, you can use your space as the delimiter and also excuse the extra space with if/then statements (test for isWhitespace, or isDigit).

Honestly, you can just use isDigit to verify the item at position [i] is in fact a digit, and just store this data in your string.

I wont write the code for you but there are a ton of workarounds for this problem... and the problem is all in your definitions of what gets stored in your String, really.