Solved

Reading two text file and output to another

Posted on 2006-06-17
11
252 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
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
 
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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:mayankeagle
mayankeagle earned 166 total points
ID: 16934107
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
IT Company 5 69
Unable to start eclipse ? 17 87
JDeveloper 12c for 32 bit 4 36
maven example error 3 36
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now