I know the exception is kind of pointless, but I was trying to learn how to use / create exceptions so I used this. The only problem is for some reason my error message generated by my exception is printing to console twice.
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
try
{
String inputFileName = null;
if (args.length > 0)
inputFileName = args[0];
File inputFile = FileGetter.getFile(
"Please enter the full path of the input file: ", inputFileName);
String outputFileName = null;
if (args.length > 1)
outputFileName = args[1];
File outputFile = FileGetter.getFile(
"Please enter the full path of the output file: ", outputFileName);
Scanner in = new Scanner(inputFile);
PrintStream out = new PrintStream(outputFile);
Person person = null;
// Read records from input file, get an object from the factory,
// output the class to the output file.
while(in.hasNext())
{
String personRecord = in.nextLine();
person = PersonFactory.getPerson(personRecord);
person.display();
person.output(out);
}
} catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
import java.util.Scanner;
class Student extends Person
{
private double gpa;
public Student()
{
super();
gpa = 0.0;
}
public Student(String firstName, String lastName, double gpa)
{
super(firstName, lastName);
this.gpa = gpa;
}
public String toString(){
try{
if (gpa >= 0.0 && gpa <= 4.0){
return super.toString() + "\n\tGPA: " + gpa;
}
else {
throw new InvalidGpaException();
}
}
catch (InvalidGpaException e){
System.out.println(e);
return super.toString() + "\n\tGPA: " + gpa;
}
}
public void display()
{
System.out.println("<<Student>>" + this);
}
@Override
public void input(Scanner in)
{
super.input(in);
if (in.hasNextDouble())
{
this.gpa = in.nextDouble();
}
}
class InvalidGpaException extends Exception {
public InvalidGpaException() {
super("Invalid GPA: " + gpa);
}
}
}
This is my console readout. Not sure what's causing the exception to print twice.
project3.Student$InvalidGpaException: Invalid GPA: -4.0
<< Student>>
Id: 2 Doe, Junior
GPA: -4.0
project3.Student$InvalidGpaException: Invalid GPA: -4.0
edit: The main code is on the top. The input is a file designated by the user. What I shown right here is my console printout, not what is returned to the output file. The output file shows the exact same thing minus the error message. The Error message from the exception (which I know is not necessary) is only printed to the console. I don't see where I'm printing it twice.