私は例外が無意味であることを知っていますが、私は例外を使用/作成する方法を学びましたので、これを使用しました。唯一の問題は、私の例外によって生成された私のエラーメッセージが何らかの理由でコンソールに2回印刷されてしまうことです。Java例外印刷2回
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);
}
}
}
これは私のコンソールです。何が原因で例外が2回印刷されるのか不明です。
project3.Student$InvalidGpaException: Invalid GPA: -4.0
<< Student>>
Id: 2 Doe, Junior
GPA: -4.0
project3.Student$InvalidGpaException: Invalid GPA: -4.0
編集:メインコードは一番上にあります。入力は、ユーザによって指定されたファイルである。私がここに示したのは、出力ファイルに返されるものではなく、私のコンソールの出力です。出力ファイルには、エラーメッセージを除いたものと全く同じものが表示されます。例外からのエラーメッセージ(私が知っているとは限りません)は、コンソールにのみ出力されます。私はそれを2度印刷しているところは見ません。
これを実行しているコード(おそらくあなたの 'main'メソッド)を見ると、最も役に立つでしょう。 –
メインコードがアップしました。 – Tyler