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:
int i = 0;
while ((line = br.readLine())!= null){
temp = line.split(" ");
for (int j = 0; j<myarray[i].length; j++) {
myarray[i][j] = Integer.parseInt(temp[j]);
}
i++;
}
Hope this helps...
Besides Joshs remark you also set the termination conditions the wrong way.
for(int i = 0; i< myarray.length; i++) {
for (int j = 0; j< myarray[i].length; j++) {
myarray[i][j] = Integer.parseInt(temp[i]);
}
}
This way you can iterate through the array but you can't use this to solve your problem. Instead you need to use 1 while-loop and 1 for-loop.
It looks to me like you're reading each line of text and then parsing that line into a 2D array. This isn't entirely correct as each line can be considered a row. Maybe you could use a counter for each line you read in your while ((line = br.readLine())!= null) loop and then only read into the row of your 2D array at the counter index... like so:
int rowCounter = 0;
while ((line = br.readLine())!= null) {
for(int i = 0; i<myarray.length; i++)
myarray[rowCounter][i] = Integer.parseInt(temp[i]);
rowCounter++;
}
As a side note, if you did want to index into a multidimensional array you also have a side problem. In both of your loops you are iterating until you reach the max number of rows. For your j loop going through the columns this might cause a problem. Instead when using a 2D loop try:
for(int i = 0; i < array.Length; i++)
for(int j = 0; j < array[0].Length; j++)
//Do some stuff
Your 'while' loop and your first 'for' loop are performing a similar task--for each line you read, you are iterating over every row in your array and filling it's columns with the line you are reading. Every value is 100 because the last line you read is full of 100s.
I suggest removing the first 'for' loop, declare 'int i = 0;' before the 'while' loop, and an 'i++' at the bottom (but inside) the for loop.
#Vivek makes a good point that you need to measure 'myArray[ i ].length' for your j counter.
Related
https://drive.google.com/a/navasotaisd.org/file/d/0B3eMFMufj6uVaVNpR0JYNnV4OTQ/view
Okay, so the problem above asks that you read in a file with a message and, using and x, y coordinate system, find the characters being read in and print out the character of that index value. I honestly have tried multiple solutions with making and array of arraylists, a arraylist of arraylists and many other failed data structures. All I need to know, is how would go about reading in the message so that I can search for it?
File f = new File("cipher.in");
f.createNewFile();
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
scan.nextLine();
ArrayList<Character> list = new ArrayList();
String code = "";
for (int i = 0; i < numOfLines; i++) {
code = scan.nextLine();
for (int j = 0; j < code.length(); j++) {
list.add(code.charAt(j));
}
}
int index = 0;
char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] = list.get(index);
index++;
if(index>=list.size())
index--;
}
}
Sorry if this problem is a bit long. It's for my class I need to turn this problem in to be able to make a 100 in the gradebook. I'm just utterly stuck and frustrated.
Try to use a hash table to store the data. You will be able to search for it later on.
The key fits quite nicely into a two-dimensional charcter array (char[][]). I would consider reading the first line (which specifies the number of lines on the key (rows of the array), and then construct the array. You have a constraint defined that a row can be no longer than 100 characters long so you can now define the complete "map".
After that i would read each line of the key, use an operator as charAt(index) and fill the map.
From there you have a very convenient structure to lookup the messages in the next part of the assignment.
Try this out , this is you code with changes and comments so that you can understand the changes and the way this code works based on the instruction in your link, I did not try to compile it, so if it has any compilation errors try to fix them. I kept your code and commented out the items that are not needed so that you can look at the differences,
File f = new File("cipher.in");
//f.createNewFile(); //* you are overwriting the file here
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
//str = scan.nextLine(); //* you just skipped one line from the numOfLInes
//ArrayList<Character> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
TreeMap charMap = new TreeMap(); //* use this to map the line number to a char array
String code = "";
for (int i = 0; i < numOfLines; i++) {
strubg code = scan.nextLine();
charMap.put(i, code.toCharArray()); //* map the line number with the char array of each line
//for (int j = 0; j < code.length(); j++) {
// list.add(code.charAt(j));
//}
}
int numOfMessageLines = scan.nextInt(); //* get the number of message lines next
for (int i = 0; i < numOfMessageLines; i++) {
string str = scan.nextLine();
string[] pairs = str.split(" "); //* each line has several key pairs for line number char number seprated by spaces
ArrayList<char> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
for(int j=0; j<pairs.length; j++)
{
string[] st = pairs[j].trim().split(","); //* example 2,13 indicate line 2 character 13 non zero indexed
int lineNum = Integer.parse(st[0]) - 1; //* zero indexed line number since we stored the lines in zero index map
int charNum = Integer.parse(st[1]) - 1; //* zero indexed char number since we stored the char array in zero indexed array
char[] chars = charMap.get(lineNum); //* get the char array for this line number
char c = chars[charNum]; //* get the character for the first message
list.add(c);
}
String message = new String(list.toArray()); //* construct the message from the char array
System.out.println(message);
}
//int index = 0;
//char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
//for (int r = 0; r < matrix.length; r++) {
// for (int c = 0; c < matrix[r].length; c++) {
// matrix[r][c] = list.get(index);
// index++;
// if(index>=list.size())
// index--;
// }
//}
Im trying to read a txt file with numbers and saving each number in a String matrix but there some things i dont get.
1.-If i run the code in Eclipse i get printed like 16 times everything and the numbers get smaller and smaller..
2.-After beeing printed there is a null value on the bottom . why?
3.-Is it ok that the variable j is beeing defined outside the while loop? or should it be inside?
Thanks fot the help!
I wrote this so far:
The text file is contains the following:
0000000000000000
0000000000000000
0000000400000000
0001111111160000
0001115111110000
0001161121510000
0001111511110000
0001110001110000
0000011311000000
0000011111000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
and the programm:
package Tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Test2 {
public static void main(String [] args){
try {
File fil = new File("/Users/MaxRuizTagle/Desktop/AbschlussprojektWiSe1415/Canberra Fox - The Key Huntress/lvl/level0.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
String s = in.readLine();
int largo = s.length();
String [][] matrix = new String [largo][largo];
String line;
int j=0;
while ((line=in.readLine() ) != null){
for (int i=0;i<16;i++){
matrix[i][j] = line.substring(i);
}
j++;
}
for(int i=0;i<16;i++){
for( j=0;j<16;j++){
System.out.println(matrix[i][j]+" ");
}
System.out.println("");
}
}catch (IOException e1){
e1.printStackTrace();
}
}
}
1) The reason that 16 blocks of numbers are printed is that you print 16 blocks of numbers here:
for(int i=0;i<16;i++){
for( j=0;j<16;j++){
System.out.println(matrix[i][j]+" "); // <-- each one a line.
}
System.out.println("");
}
The reason that they get shorter is that you previously saved ever shorter substrings here:
for (int i=0;i<16;i++){
matrix[i][j] = line.substring(i); // <-- substring from pos i to end
}
You weren't very clear about your requirements, so I have to guess a little; it looks to me as though what you wanted to do was extract strings of one character each:
for (int i=0;i<16;i++){
matrix[i][j] = line.substring(i, i + 1); // substring from i to i + 1
}
And later print each column in a line (transposing the image):
for(int i=0;i<16;i++){
for( j=0;j<16;j++){
System.out.print(matrix[i][j]+" "); // print instead of println
}
System.out.println("");
}
Although I wonder why you bother with an array of Strings if you could use a char[][] matrix and line.charAt(i) or save the lines as they come and extract individual characters as lines[j].charAt(i) in the output loop.
2) You discard a line in the beginning:
String s = in.readLine();
int largo = s.length();
// s is not used after this
because of this, your matrix shrinks from 16x16 to 15x16, and the loop
while ((line=in.readLine() ) != null){
...
doesn't initialize the last column of matrix, which remains filled with nulls. The least invasive fix for that would be to, well, treat the first line in the loop like all others, as in
String line = s;
while(line != null) {
...
line = in.readLine();
}
3) I see no problem with that.
4) The way you treat your array dimensions is a bit odd. You appear to read them from the file, but later they're hard-coded. If your code is only going to work with a 16x16 matrix, why do you bother with largo, and if it should work with matrices of other sizes, why is the size of 16 hardcoded everywhere else?
2.-After beeing printed there is a null value on the bottom . why?
Because the first line is not put in the matrix, you only use that for s.length().
Then the while loop will use only the 15 remaining lines, instead of 16.
As a result, the last j index will have null values.
3.-Is it ok that the variable j is beeing defined outside the while loop? or should it be inside?
It's not great to be outside and reused. It's better to declare it inside.
Maybe you're looking for something more like this:
for (int j = 0; j < 16; j++) {
matrix[0][j] = String.valueOf(s.charAt(j));
}
for (int i = 1; (line = in.readLine()) != null; ++i) {
for (int j = 0; j < 16; j++) {
matrix[i][j] = String.valueOf(line.charAt(j));
}
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
I have a .txt file with 1302 lines, which divides evenly to 14 x 93 (corresponding to 14 columns and 93 rows). I would like to parse the 1302 lines into a [93][14] multi-dimensional array. I have the following script that traverses each individual "cell", but as for the file parsing, I have some questions.
int rows = 93;
int columns = 14;
int i;
int j;
int count = 0;
String[][] array = new String[rows][columns];
for(i = 0; i < rows; i++){
for(j = 0; j < columns; j++){
System.out.println(i + "," + j);
count++;
}
}
How do I assign each "line" of the text file into each cell?
My Recommendation (aside from changing using double[][] to something like List<List<Double>>) would be to go through each text line as such:
InputStream fis;
BufferedReader br;
String line;
fis = new FileInputStream("the_file_name");
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = br.readLine()) != null) {
// Deal with the line
}
// Done with the file
br.close();
br = null;
fis = null;
With this, you should be able to get each individual 'line' of the file. The reason I mention above using the List<List<Double>> instead of double[][] is because you get two things out of that:
1) dynamic resizeability. Even if you know the size and want to give that list a default size to help with performance, you aren't LIMITED to that size, which is worth it's weight in.. flops? programmers gold.
2) using the primitive double (lowercase d) as opposed to the Java object Double (uppercase D) really kill you as far as not getting access to a LOT of great methods and useability built into Double (capitol D object). for more explanation on this, see: Double vs. double
Also note, the code above has no error checking, so you'll want to build some of that into it, it's a pretty basic implementation.
EDIT::
Alright, so in your code that you posted at: code snipped you have a double for-loop INSIDE of the readLine() loop. like so:
while ((line = br.readLine()) != null) {
for (int i = 0; i < rows; i++){
for(int j = 0; j< columns; j++){
line = array[i][j];
}
}
}
Now, there are two problems with this:
1) you are setting LINE equal to the content of array[i][j] which means nothing, since array is just an empty 2-dimensional array.
2) for EVERY line in the text file you are looping 1302 times (and then some more because you're doing (1302 * columns) * 1302
really what this code above does, is it takes care of your 'row' loop. so instead of what you're doing, just do:
int i = 0;
while ((line = br.readLine()) != null) {
array[i][0] = line;
i++
}
that will fill up your array with all of the strings from the file.
Read in the lines (rows) with Scanner or BufferedReader, then use split("\\s+"); to split the lines into tokens (columns). Then use Double.parseDouble() on each of the tokens and then insert it into your array.
In order to assign anything to a 2D matrix, you can do something like this:
for (int r=0; r<NUM_ROWS; r++)
for (int c=0; c<NUM_COLS; c++)
matrix[r][c] = get_line(r*NUM_COLS + c)
Where get_line(i) will get the i'th line in the file
Alright, lets try this again, sorry for the poor title I don't know what to call this. I haven't done much File I/O before, I personally think Java is absolutely terrible at it but nonetheless I have to do it.
A bit of background information, this is my Conway's Game of Life project, and all of my other code works fine I just need to do the I/O now.
I'm reading in from a text file, that looks like this.
So what this does is the first two numbers are the size of that the array needs to be, the String after them is irrelevant. And after that is the array of the cell arrangement in this example it's that of the glider. Now my problem is that I don't know how to store the first line in a String, and the rest in an array. Below is what I've done, and brace yourselves for a Big O of n^∞.
public char[][] fileIO(){
ArrayList<String> list = new ArrayList<String>();
char[][] newArray;
String[] tokens;
BufferedReader reader;
String inputLine;
try{
reader = new BufferedReader(new FileReader("untitled.txt"));
while((inputLine = reader.readLine()) != null){
list.add(inputLine);
}
reader.close();
}catch (IOException e){
System.out.println(e);
}
tokens = list.get(0).trim().split("\\s+");
newArray = new char[Integer.parseInt(tokens[0])][Integer.parseInt(tokens[1])];
for(int row = 0; row < newArray.length; row++){
for(int col = 0; col < newArray[row].length; col++){
for(int line = 1; line < list.size(); line++){
for(int Char = 0; Char < list.get(line).length(); Char++){
newArray[row][col] = list.get(line).charAt(Char);
}
}
}
}
return newArray;
}
I know there's a lack of comments, so I'll try to explain what I tried to do now;
I read from the file and stored it all in an ArrayList
Got the tokens of the first like (10 20 Glider), and created an instantiated an array with the values 10 and 20
Then proceeded to loop through the array's rows and columns, then each line of the inputted array, and then looped through each character of that line to add into the array at their respected positions.
However, this doesn't seem to be working and I'm sure there is a much simpler and efficient way of doing this. So I ask again, can anyone tell me of a simpler way of doing this I/O? I don't need the code, just an explanation of how to do so.
In this:
for(int row = 0; row < newArray.length; row++){
for(int col = 0; col < newArray[row].length; col++){
for(int line = 1; line < list.size(); line++){
for(int Char = 0; Char < list.get(line).length(); Char++){
newArray[row][col] = list.get(line).charAt(Char);
}
}
}
}
You have two outer loops that are browsing through your newArray grid, and two inner loops that are browsing through the lines of the file. By doing that, you are essentially writing every char of every lines of your file into each cell of your grid, one after the other. In the end, you will have the last character of the last line of your file in all the cells of newArray. This is probably not what you want to do.
Edit: If I understand correctly, the number at the beginning of the file are the number of lines and the number of columns of the data that follow. Then you just have to use the two outer loops, and use row and col to access respectively the line in list and the character in the line.
I' re-doing an exam for practicing and i've almost completed it. The only problem i have is with this part:
int z=0,x=0;
String line="";
RandomAccessFile read = new RandomAccessFile(s, "rw");
while((read.readLine())!=null)
z++;
read.seek(0);
while(x<z){
line=read.readLine();
StringTokenizer stk = new StringTokenizer(line, " ");
if(line.charAt(0)=='r'){
nr=z;
nc=stk.countTokens()-1;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc; j++)
valori[i][j] = Integer.parseInt(stk.nextToken());}
}
else if(line.charAt(0)=='c'){
nr=stk.countTokens()-1;
nc=z;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc-1; j++)
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;
Basically i have to read a file where i have the description of a matrix as follows:
c 0 1 0
c 0 0 1
c 0 0 0
c 1 0 0
And the resulting matrix would be
|0|0|0|1|
|1|0|0|0|
|0|1|0|0|
After reading the file i have to build the matrix with a 2d int array, i used the same code from another exercise but when using stk.nextToken() i get java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source)
I cannot find the error, 2d arrays are correctly initialized and filled.
Thanks in advance for any help.
The "Unknown Source" part of the exception is an effect of running your code through the jre instead of the JDK. If you run with the JDK, your runtime environment will have access to the debug info and proper line numbers will be printed instead.
a quick look suggests that this section is in error:
nr=stk.countTokens()-1;
nc=z; //z == # of rows
//first pass through = hasMoreTokens == true (a total of 4: C,0,1,0)
while(stk.hasMoreTokens()){
//first token - C
stk.nextToken();
//this will iterate 3 times
for(int i = 0; i < nr; i++)
//this, too, will iterate 4 times - a total of 12 times considering
// the outer loop
for(int j = 0; j < nc-1; j++)
// after 3 passes, this will throw the exception
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;
This error means that there are no more tokens in the StringTokenizer remaining, and you are asking for a one more token. "Unknown source" is not relevant to your problem - this just means you have no access to the source code of the Java system library but I doubt it will be helpful.
This happens because the line you read from the file contains less space delimited tokens than you expect.
The error happens because you are tokenizing one single line, and in the two for loops you are reading columns and rows.
Instead of using the StringTokenizer with while loops I would recommend to use the .split command:
int j=0;
// read all rows
while((read.readLine())!=null) {
String line=read.readLine();
String[] columns=line.split(" ");
// read columns of each row
int i=0;
for (String column: columns) {
if (!column.equals("c")) {
valori[j][i] = Integer.parseInt(column);
}
i++;
}
j++;
}
PS: Pseudo code above, untested.