Reputation: 185
I have got n lines of numbers , all containing equal number of numbers lets say m , how to store them in 2d array
1 5 7 9
2 3 4 6
3 4 5 8
Note that here value of n and m is not given .
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
while(sc.hasNextLine())
{
String line=br.readLine();
String [] str =line.trim().split(" ");
int n=str.length;
columns=n;
for(int i=0;i<n;i++)
{
matrix[rows][i]=Integer.parseInt(str[i]);
}
rows++;
}
Runtime error is coming
Runtime error time: 0.14 memory: 321088 signal:-1
Upvotes: 1
Views: 103
Reputation: 522406
You can temporarily store everything into an ArrayList
, then iterate over it at the end and create your 2D array:
BufferedReader br = new BufferedReader("C:/YourFile.txt");
ArrayList<Integer> list = new ArrayList<Integer>();
int rows=0, cols=0;
String line;
while ((line = br.readLine()) != null) {
String [] str = line.trim().split(" ");
int n = str.length;
cols = n;
for (int i=0; i < n; ++i) {
list.add(Integer.parseInt(str[i]));
}
++rows;
}
// now create a 2D array and store everything into it
int[][] array = new array[rows][cols];
for (int i=0; i < rows; ++i) {
for (int j=0; j < cols; ++j) {
array[i][j] = list.get(i*cols+j);
}
}
Upvotes: 2
Reputation: 1638
Not sure, but I think using System.in
in two objects (Scanner
and InputStreamReader
) causes issues, as characters may be consumed by the scanner before being read by the reader.
If you leave away the scanner, and just use BufferedReader.ready()
in your while condition, it works (nearly the same code) :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(br.ready())
{
String line=br.readLine();
String [] str =line.trim().split(" ");
int n=str.length;
columns=n;
for(int i=0;i<n;i++)
{
matrix[rows][i]=Integer.parseInt(str[i]);
}
rows++;
}
You might prefer Tichodroma's more elegent answer.
Upvotes: 1
Reputation:
Try this:
List<List<Integer>> ints = new ArrayList<>();
String d = "1 5 7 9 \n"
+ "2 3 4 6 \n"
+ "3 4 5 8 ";
for (String line : d.split("\n")) {
List<Integer> row = new ArrayList<>();
for (String cell : line.split(" ")) {
row.add(Integer.parseInt(cell));
}
ints.add(row);
}
System.out.println(ints);
Output:
[[1, 5, 7, 9], [2, 3, 4, 6], [3, 4, 5, 8]]
Upvotes: 1