I’m new to Java programming…
I’m trying to read data from text file and save it into 2D array. So basically, program will receive parameter (IP) and look for the file with same IP number.
And the program will read each line and store into an 2D array.
My attempt:
String ipNum = request.getParameter("ipNum");
String root = getServletContext().getRealPath("/");
String dailyPath = root + "\\" + ipNum +".txt";
int[][] myarray = new int[3][6];
BufferedReader br = new BufferedReader(new FileReader(dailyPath));
String line = " ";
String [] temp;
while ((line = br.readLine())!= null){
temp = line.split(" ");
for(int i = 0; i<myarray.length; i++) {
for (int j = 0; j<myarray.length; j++) {
myarray[i][j] = Integer.parseInt(temp[i]);
}
}
}
Data:
CPU 30 30 30 30 30 30
RAM 70 70 70 70 70 70
HAR 80 80 80 80 80 80
NET 100 100 100 100 100 100
the problem that I’m having is that when I call array, I always get 100 or 0 (assuming empty)
so for example myarray[1][2] should output 30 but i get 100
myarray [2][4] = 70 but i get 100…
I tried to play around with the code for past few hours, I can’t figure it out…is my whole code wrong or something?
Thanks for help!
Yeah, you are iterating twice and therefore filling your array with the last value… try this code:
Hope this helps…