Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class ReadANDWright
- {
- public static void main(String args[]) throws IOException
- {
- // C:\\Documents and Settings\\346778\\My Documents\\TextFiles\\StudentScores.txt
- // C:\\Documents and Settings\\Roland.USER-6FEF0AE329\\My Documents\\JavaProgramsMade\\JavaLessons\\TextFiles\\StudentScores.txt
- // I want to make these long file paths far shorter than they are so I don't have to type them in each time and I can save and load from at least one file/directory above what the classes are in.
- Scanner sf = new Scanner(new File("C:\\Documents and Settings\\Roland.USER-6FEF0AE329\\My Documents\\JavaProgramsMade\\JavaLessons\\TextFiles\\StudentScores.txt"));
- int maxIndx = -1; //-1 so when we increment below, the first index is 0
- String text[] = new String[1000]; //To be safe, declare more than we need
- while(sf.hasNext( ))
- {
- maxIndx++;
- text[maxIndx] = sf.nextLine( );
- //System.out.println(text[maxIndx]); //Remove rem for testing
- }
- //maxIndx is now the highest index of text[], -1 if no text lines
- sf.close( ); //We opened a file above, so close it when finished.
- FileWriter fw = new FileWriter("C:\\Documents and Settings\\Roland.USER-6FEF0AE329\\My Documents\\JavaProgramsMade\\JavaLessons\\TextFiles\\StudentScores2.txt",true);
- PrintWriter output = new PrintWriter(fw);
- String answer = ""; //We will accumulate the answer string here.
- int sum, FF; //accumulates sum of integers
- int Div;
- for(int j =0; j <= maxIndx; j++)
- {
- Scanner sc = new Scanner(text[j]);
- sum = 0; //important to set to 0; otherwise it will remember the last sum
- FF = 0;
- Div = 0;
- answer = ""; //otherwise it will remember last answer String
- answer = sc.next();
- while( sc.hasNextInt( ) ) //We could also have used hasNextInt( ) here
- {
- int i = sc.nextInt( );
- FF++;
- sum = sum + i;
- }
- Div = (int)Math.round((double)sum / (double)FF);
- //answer = answer + " = " + sum + " / " + FF + " = " + Div;
- answer = answer + ", " + "average = " + Div;
- output.println(answer);
- //System.out.println(answer);
- }
- output.close( ); //These two lines are very important. Some of the data
- fw.close( );//may not actually be put on disk until you close.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement