counting the values in input file and and writing the output to a file
Can any one please correct this code. This is to read a file and later it should write the output to a file. Input file has 20 rows and 4 columns. If we have 1 in the 1st column of the input file then it should count all 1's and write those 1s counted value to a file.
Code:
import java.io.*;
import java.util.*;
import java.lang.ClassNotFoundException;
class Code
{
public static void main(String[] args) throws IOException
{
String str[][] = new String[20][4];
FileReader fr = new FileReader("in.txt");
BufferedReader br = new BufferedReader( fr );
FileWriter fw = new FileWriter("out.txt");
PrintWriter pw = new PrintWriter(fw);
String line = "";
int i = 0, j= 0, one=0, two=0,three=0;
while( ( line = br.readLine() ) != null )
{
StringTokenizer tok = new StringTokenizer(line, ", ");
if(str[i][0].equals("1") )
{
one = one++;
}
else if(str[i][0].equals("2") )
{
two = two++;
}
else if(str[i][0].equals("3") )
{
three = three++;
}
i++;
}
br.close();
fr.close();
System.out.println("Sending the output to file:");
for(i=0;i < 20; i++)
{
for(j=0;j<4; j++)
{
System.out.printf("one" +one);
pw.print(one);
System.out.println("two" +two);
pw.print(two);
System.out.println("three" +three);
pw.print(three);
}
pw.println();
}
pw.close();
fw.close();
}
}
Re: counting the values in input file and and writing the output to a file
Quote:
Can any one please correct this code
We can help YOU correct it, provided you tell us what's wrong in the first place. And please use the code tags, and please be forthright when crossposting
This thread has been cross posted here:
http://www.roseindia.net/answers/viewqa/Java-Beginners/26756-counting-the-values-in-input-file-and-and-writing-the-output-to-a-file.html
Although cross posting is allowed,
for everyone's benefit, please read:
Java Programming Forums Cross Posting Rules
The Problems With Cross Posting
Re: counting the values in input file and and writing the output to a file
As i am new to these forums i really don't know about this. I have gone through the links which you have mentioned about the cross posting. Thanks for telling this.
I didn't get what you are asking about. " provided you tell us what's wrong in the first place. "
Re: counting the values in input file and and writing the output to a file
You are accessing your String Array from the While loop, but you haven't populated it with anything. That is going to throw and error. The next problem is that you are breaking up the input line with StringTokenizer, but you don't do anything with the data. Your while loop isn't actually comparing and counting any of the input data so your output file is just going to be a bunch of zeros.
We need some more clarification on what exactly the program should be doing. I don't understand exactly what should be output into a file and what you are trying to count from the input.