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
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+");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments