Solved

Reading two text file and output to another

Posted on 2006-06-17
11
262 Views
Last Modified: 2008-03-06
I'm a novice trying to use Java, how do you read two text file and output to another text file?

Text file InAction
2333021      Bokow, R.         NS201      3  A
2333021      Bokow, R.         MG342      3  A
2574063      Fustil, D.         CM201      3  C
2574063      Fustil, D.         CP101      2  B
2663628      Kingsley, M.  MK341      3  A
2663628      Kingsley, M.  CP101      2  B

Text file InMaster
2333021    Bokow, R.        48       4.0
2574063    Fustil, D.         12       1.8
2663628    Kingsley, M.     36       3.5

The output should look something like this:

Student         Student       Course        Course
ID Number       Name          Credits       GPA
2333021         Bokow, R.        3           4.0
2574063            Fustil, D.         12          1.8
2663628            Kingsley, M.     36               3.5

Here is the code I have been working with:

public static void main(String[] args)
    {
          DecimalFormat form = new DecimalFormat("0.0");
             String saveID;
             String StudentIDNumber;
            String StudentName;
            String init;
            String CourseCode;
            String credits;
            int CourseCredits;
            int Points = 0;
            int Credits = 0;
            int ID = 0;
            String grade;
            String CourseGrade;
            double gpa;
            
            StringTokenizer st, st2;

            try
            {
            FileReader frInAction = new FileReader( "C:\\InAction.txt" );
            BufferedReader inAction = new BufferedReader(frInAction);
                  
            FileReader frInMaster = new FileReader( "C:\\InMaster.txt" );
            BufferedReader inMaster = new BufferedReader(frMaster);
                  
            FileWriter fw = new FileWriter( "C:\\OutMaster.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw);
      
            String inLine = inAction.readLine();
                  
            st = new StringTokenizer(inLine);
              
                  StudentIDNumber = st.nextToken();
                  StudentName = st.nextToken();
                  
                  out.println( "Student         Student       Course        Course");
                  out.println( "ID Number       Name          Credits       GPA");
                                    
                  saveID = StudentIDNumber;                  
                        
                while (inLine != null)
              {
                          st = new StringTokenizer(inLine);
                        StudentIDNumber = st.nextToken();
                        StudentName = st.nextToken();
                        init = st.nextToken();
                        StudentName = StudentName + " " + init;
                        CourseCode = st.nextToken();
                        credits = st.nextToken();
                        CourseCredits = Integer.parseInt(credits);
                        CourseGrade = st.nextToken();
                        if( !saveID.equals(StudentIDNumber))
                        {
                  //Calculate GPA and output total lines for previous student
                  String inLine2 = InMaster.readLine();
                  st2 = new StringTokenizer(inLine2);
                  StudentIDNumber = st2.nextToken();
                  StudentName = st2.nextToken();
                  init = st2.nextToken();
                  StudentName = StudentName + " " + init;
                  credits = st2.nextToken();
                  CourseCredits = Integer.parseInt(credits);
                  CourseGrade = st2.nextToken();
                  gpa = Double.parseDouble( CourseGrade);
                  Points += CourseCredits * gpa;
                  Credits += CourseCredits;
                  gpa = (double)Points/Credits;
                  out.println(Credits);
                  out.println(form.format(gpa));                                          
                  //Reset accumulators
                  Points = 0;
                  Credits = 0;
                  saveID = StudentIDNumber;
                        }
                  char Grade  = CourseGrade.charAt(0);
                  int score = 0;
                  if ( Grade == 'A')
                  {
                    score = 4;
                    Credits = Credits + CourseCredits;
                  }
                  else if (Grade == 'B')
                  {
                    score = 3;
                    Credits = Credits + CourseCredits;
                  }
                  else if (Grade == 'C')
                  {
                    score = 2;
                    Credits = Credits + CourseCredits;
                   }
                   else if (Grade == 'D')
                   {
                     score = 1;
                     Credits = Credits + CourseCredits;
                   }
                   else if (Grade == 'F')
                   {
                    score = 0;
                   }
                   Points = Points + score * CourseCredits;
                           
                   inLine = inAction.readLine();
                   //Calculate GPA and output total lines for previous student
                    double gpa;
                    gpa = (double)Points/Credits;
                    out.println(Credits);
                    out.println(form.format(gpa));                        
                                    
                   //Output header lines for new student just input
                   out.println( "Student         Student       Course        Course");
                   out.println( "ID Number       Name          Credits       GPA");
                  
                  //Reset accumulators
                  Points = 0;
                  Credits = 0;
                  saveID = StudentIDNumber;
                  }
            }
out.println(StudentIDNumber + "         " + StudentName + "        " + Credits + "           " + CourseGrade);
//JOptionPane.showMessageDialog(null, CourseCode + "   " + CourseCredits + "       " + CourseGrade );
                  inLine2 = InMaster.readLine();
                                  gpa = (double)Points/Credits;
                              
                  inAction.close();
                  inMaster.close();
                  out.close();
      JOptionPane.showMessageDialog(null, "File operation complete" );
           }
            catch( Exception ex )
            {
                  ex.printStackTrace();

            
    }  
}
0
Comment
Question by:daddyrat
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 26

Expert Comment

by:ksivananth
ID: 16928884
how did u get the course credit values?
0
 
LVL 9

Accepted Solution

by:
matthew016 earned 168 total points
ID: 16928946
Here u have tutorials on reading and writing from/into files

http://javaalmanac.com/egs/java.io/pkg.html
http://javaalmanac.com/egs/java.io/WriteToFile.html
0
 

Author Comment

by:daddyrat
ID: 16929748
I didn't, still trying to piece it together.  The correct outMaster file value should read:
   51  17  42
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 1

Assisted Solution

by:FunnyMan
FunnyMan earned 166 total points
ID: 16929860
Okay, looks like what's supposed to be going on here is an update of student GPA's and credit hours based on the incoming data for the current semester.  In which case, here's what you want to do:

Read in InMaster, parse it into four pieces (id (int), name (String), totalCredits (int), gpa (double)) for each row and store them in an array. (Be careful that the space in the name doesn't throw you off.)
Read in InAction. For each line:
Parse it into five pieces (id (int), name (String), course (String), credits (int), grade (int)).  Discard course, it's unimportant to us.  (Parse grade the same way you did before)
Find the array index with a maching id.  (If you're expecting there to be new students, store the array as a Vector instead, so that adding a new record is easy)
On that row, do these operations:
gpa = (gpa*totalCredits + grade*credits)/(totalCredits + credits);
totalCredits += credits;  (i.e. totalCredits = totalCredits + credits)

Then just build your file by using a PrintStream wrapped around a FileWriter.  The PrintStream works just like System.out.

-FM
0
 
LVL 1

Expert Comment

by:FunnyMan
ID: 16929866
Note that you have two options for the "array" of the master data.  You can either store it as a set of four arrays (or, equivalently, Vectors) or you can define a private class inside of your program class that just has the four pieces of information as public fields, and then drop those into the array/Vector.

-FM
0
 

Author Comment

by:daddyrat
ID: 16930829
I'm trying to understand, but I'm lost.  Sorry
0
 

Author Comment

by:daddyrat
ID: 16930838
I haven't gave up!!
0
 
LVL 1

Expert Comment

by:FunnyMan
ID: 16930901
I won't do your homework for you, but I'll help you with it.  You've got all the pieces you need.  The code you put up already handles the basic steps you need, you just need to get them organized the right way and use either arrays or vectors to hold on to the information while you work with it.

I'd suggest working with four vectors, that'll be the easiest way to do it.  I'll even show you how.  The basic thing to remember is that a vector acts like an ordered list.  The first item you put in has the number (called an *index*) 0, the second 1, and so on.

Setup:
Create four vectors, ids, names, creditTotals, gpas, like so:
Vector<Integer> ids = new Vector<Integer>();
Vector<String> names = new Vector<Integer>();
And so on.

Parsing of InMaster:
Use a while loop (like before) to step through the input file one line at a time and decode (called *parsing*) its pieces.  When you get a piece of information, say the id, you save it into the vector like this:
ids.add(id);
As long as you always add one item to each vector (like you will when parsing), the index of the id will also be the index of its matching name, creditTotal, and gpa in the three other vectors.

Parsing of InAction:
Again, use a while loop to step through the input file and parse each line.  Once you've got it all parsed, get the index you want like this:
int index = ids.indexOf(id);

The two math lines look a bit different now:
/*This line is the first half of "gpa =".  It's more complex, because we have to save it in the right spot in the vector. */
gpas.setElementAt(
  /* This line corresponds is the math in the first line before. Again, more complex because we need to get the creditTotal out of the vector.*/
  (gpas.get(index) * creditTotals.get(index))/(creditTotals.get(index) + credits)),  
  /* This line is the second half of "gpa ="
  index);
/* And the second line. */
totalCredits.setElementAt(creditTotals.get(index) + credits, index);

Looks like you've already got "out" set up.  Use this for loop to go through the vectors and print out your data.
for (int index = 0; index < ids.getSize(); index++)
{
  /* The out.println from above goes here.  You'll need to adapt it to pull the information out of the vectors.  Also, you'll need to play around with the strings in it and whether you want to do some additional output outside of this loop in order to get the exact output you want. */
}

Good luck.
-FM
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 166 total points
ID: 16934107
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question