JAVA HELP!

chrome0011

Member
Mar 13, 2005
145
0
0
Ok, this assignment is to read a list of grades from a .txt file and find the averages, and assign a grade, and send the output to another .txt file. Here's my source so far, and the error messages i'm getting. Any help is GREATLY appreciated.
------------------------------------
package Lab2;

/*This program reads a student's name and test scores.
*It then computes average test score for each student and assigns
*appropriate grade.
*/


import java.io.*;
import javax.swing.*;
import java.util.*;

public class Lab2 {//start class Lab2


public static float calculateAverage(StringTokenizer token, PrintWriter outFile)
{//this method returns values for avg of scores.
float total = 0;

while (token.hasMoreTokens()) {
String m = token.nextToken();
int i = Integer.parseInt(m);
total = (total + i);
}//end while
float avg = (total / 5);
return avg;
}//end method calculateAverage

public static char calculateGrade(double avg)
{//this method determines and returns each student's grade.
char grade;
if (avg < 60)
grade = 'F';
else if (avg >= 60 && avg < 70)
grade = 'D';
else if (avg >= 70 && avg < 80)
grade = 'C';
else if (avg >= 80 && avg < 90)
grade = 'B';
else if (avg >= 90 && avg <= 100)
grade = 'A';
return grade;
}//end method calculateGrade

public static void main(String[] args)
{//main method- opens studentfile.txt, sends output to studentout.txt,

BufferedReader inFile = new BufferedReader (new FileReader ("D:\\studentfile.txt"));
PrintWriter outFile = new PrintWriter (new FileWriter ("D:\\studentout.txt"));

outFile.println ("Student Test1 Test2 Test3 Test4 Test5 Average Grade");

String s;
while ((s = inFile.readLine()) != null) {
outFile.println (s);
StringTokenizer token = new StringTokenizer (s);
float avg = calculateAverage (token, outFile);
char grade = calculateGrade (avg);
outFile.println (avg + " " + grade);
}//end while

}//end main
}//end class Lab2
---------------------------
error: unreported exception: java.io.FileNotFoundException; must be caught or declared to be thrown.
(this is on the BufferedReader line)
error: unreported exception: java.io.IOException; must be caught or declared to be thrown.
(this is on the PrintWriter line)

I realize I need a few more lines of code in the main method, but I am stuck as to why the compiler cannot find the input and output files.... :confused:
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
Before you initialize a file, put it in a try { } block. Then following the end bracket of try {}, you do catch( FileNotFoundException ex ) {}. Same as the other error probably (so catch(IOException) {} ). And in that catch {} block you can have it print or something to let you or the user know about the kind of error. Basically, the code you wrote could potentially generate an error and so you "try it" and if there is an error you "catch it" (the exception is thrown). Hopefully this sounds familar from your instructor?

If you don't understand what I'm saying just try googling 'try catch java' or whatnot.. it's a decent concept to understand. :)




Also, this may been an ahole kind of remark, but for instance when you declare

public class Lab2 {} ...


Is there any reason to comment // start of Lab2 class ???


I know it's sort of taught in school, and when I started Intro Java courses I almost did the same, but really why comment a class declaration (with a simple //, an actual explanation of the algorithm/whatever is different)? The only reason I see to comment 'end if', 'end for', etc (which I seen A LOT of people do in class) is if you have trouble with matching brackets but even then, thats just during testing, and an editor that supports collapsible methods will help you find the missing bracket much easier.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
the problem is that you need to handle those exceptions in the code. read up on exception handling. but if you want a quick and dirty solution to get that code compiling, just add "throws FileNotFoundException, IOException after public static void main(String[] args)
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Also, if you get the chance, look into getting a nice IDE. It'll spot these errors for you before compile, highlight other warnings/errors for you and provide tentative solution, and can give you some autocompletion. Eclipse, Netbeans, I think JCreator, too.
 

chrome0011

Member
Mar 13, 2005
145
0
0
package Lab2;

/*This program reads a student's name and test scores.
*It then computes average test score for each student and assigns
*appropriate grade.
*/


import java.io.*;
import javax.swing.*;
import java.util.*;

public class Lab2 {


public static float calculateAverage(StringTokenizer token, PrintWriter outFile)
{//this method returns values for avg of scores.
float total = 0;

while (token.hasMoreTokens()) {
String m = token.nextToken();
int i = Integer.parseInt(m);
total = (total + i);
}//end while
float avg = (total / 5);
return avg;
}//end method calculateAverage

public static char calculateGrade(double avg)
{//this method determines and returns each student's grade.
char grade = 'o';
if (avg < 60)
grade = 'F';
else if (avg >= 60 && avg < 70)
grade = 'D';
else if (avg >= 70 && avg < 80)
grade = 'C';
else if (avg >= 80 && avg < 90)
grade = 'B';
else if (avg >= 90 && avg <= 100)
grade = 'A';
return grade;
}//end method calculateGrade

public static void main(String[] args)
{//main method- opens studentfile.txt, sends output to studentout.txt,
try {

BufferedReader inFile = new BufferedReader (new FileReader ("D:\\studentfile.txt"));
PrintWriter outFile = new PrintWriter (new FileWriter ("D:\\studentout.txt"));

outFile.println ("Student Test1 Test2 Test3 Test4 Test5 Average Grade");

String s;
while ((s = inFile.readLine()) != null) {
outFile.println (s);
StringTokenizer token = new StringTokenizer (s);
float avg = calculateAverage (token, outFile);
char grade = calculateGrade (avg);
outFile.println (avg + " " + grade);
}//end while
}//end try
catch (Exception e) {
System.out.println("Exception: " + e);
}//end catch

}//end main
}//end class Lab2
------------------
Ok, got the catch in there. And I'm still missing code to display the output correctly, but shouldn't, for example,

outFile.println ("Student Test1 Test2 Test3 Test4 Test5 Average Grade");

..at least print that output to the outFile?

Forgive my noobery.... lol... but I've only taken a C++ intro class so far, and I like to kick it barney style. Thanks for the replies so far! (and I fixed the //start class stuff... like I said tho, like to keep it painfully clear..:D) If it helps I'm using Borland's JBuilder.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
It's probably good practice to flush() and close() the PrintWriter once you're done with it.
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
Outfile? I'm not familar with that, but the most simplest, quickest way of debbugin is System.out.println(stringName). If you would like it in an output file you can probably redirect with java programName > output.txt. Not too sure tho...


Actually, now that I've read your OP, I think you can just read from System.in, output to System.out, and use java progName < input > output... Should take care of that. And the StreamTokenizer and/or Scanner should be able to read numbers without much work.
 

chrome0011

Member
Mar 13, 2005
145
0
0
I have to use the FileWriter and FileReader objects as part of the assignment... :( ... anyone else have any advice as to how to get this to output to a .txt file?
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
Right, you can still specify: ... new FileReader( System.in )
and: ... FileWriter( System.out )


System.in reads from the keyboard at the console and System.out writes to the display at the console, but by running 'java progName < studentin.txt > studentout.txt, it will redirect the input to be from the file and redirect the output to a file. Of course, I don't know why your code doesn't read/write as it is, but redirection should work, IF it is allowable by the instructor, since it will need to be run with that syntax.
 

chrome0011

Member
Mar 13, 2005
145
0
0
Isn't that what those two commands are supposed to do by themselves? I'm pretty sure I will not be allowed to use that sort of command. Of course, I won't know til monday. Is my syntax correct on the input and output?
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
Yeah I was mentioning the use of file redirection as an alternative way to input and output, since I don't know why your code doesn't work. I've BARELy used file I/O and it was with FileInputStream and FileOutputStream but it looks like FileReader and FileWriter are just more convenient classes. I don't think this would cause it to not output, but you are suppose to close your output file when done writing to it, so outFile.close() after you are done.
 

chrome0011

Member
Mar 13, 2005
145
0
0
Well, in any case, I really appreciate you trying to help out...! I'm sure I'll get a definitive answer on Monday. Maybe I'll get lucky and the answer will come to me in a dream or something. I'm sure it's something small. Thanks again dura, and everyone else! :D
 

MartyMcFly3

Lifer
Jan 18, 2003
11,436
29
91
www.youtube.com
you need to add outFile.close(); at the end or else the output file wont be saved/created at all.

edit: it'd help if i read the rest of the thread so i dont sound like a broken record. :p
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
I just compiled your code - seems to work, with the flush and close methods. Some minor changes remain in the assignment, I think.

 

chrome0011

Member
Mar 13, 2005
145
0
0
Ok, this is the final version of the Lab. I realize that I could use a loop in the calculateAverage method, but I'm just happy it works right now!!! Give it a try... you'll have to create the .txt files in the appropriate location. Now all of those teachers with exactly five grades can rest easy... my little Lab will do their grading...:confused:

edit: and I don't know why these tabs didn't work correctly...:(