我这里有这段代码,需要检测输入文件中的任何行是否不包含名字,姓氏或等级。然后,它需要为不正确的行引发有意义的异常。我在设置if
语句以检测每行内容时遇到麻烦。我知道inputFile.next
一次只能读一个字,我很确定我需要为整行创建另一个变量并合并inputFile.nextLine
。如果我从输入文件中取出名称或等级,则会抛出ArrayOutOfBounds
异常,因为它希望看到三个单词。我想我真正想问的是如何检查行中是否包含三个单词。这是我的代码示例...
(被注释掉的代码部分是作业的另一部分,需要检查是否任何成绩在0到100之间,如果是,则抛出异常,这部分我可以正常运行。)>
我的输入文件:
迈克·托尼98.7
玛丽汤姆65.8
安·托马斯95.1
亚历克斯·莱德178.6
package classwork11_2;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Classwork11_2 {
public static void main(String[] args)throws IOException{
File input = new File("students.txt");
Scanner inputFile = new Scanner(input);
PrintWriter output = new PrintWriter("average.txt");
ArrayList<Student> array = new ArrayList<>();
double average = 0;
String name = "";
String header = "Average:";
double sum = 0;
while(inputFile.hasNext()){
String firstLine = inputFile.nextLine();
String[] word = firstLine.split(" ");
String fName = inputFile.next();
String lName = inputFile.next();
String grades = inputFile.next();
try{
/*double g = Double.parseDouble(grades);
if(g < 0 || g > 100)
throw new MyException(g);*/
if(word[0] == null || word[1] == null || word[2] == null)
throw new MyException("The names don't exist");
}
catch(MyException e){
System.out.println("Parsing line with " + fName + " " + lName + "
" + grades + " gave the following error: " + e.getMessage());
}
Student student = new Student(fName, lName, grades);
array.add(student);
name += student.getfName() + " " + student.getlName() + ", ";
}
for(Student i : array){
double num = Double.parseDouble(i.getGrade());
sum += num;
average = sum / array.size();
}
System.out.println(name.substring(0, name.length()-2));
System.out.printf("%-15s%10.1f\n", header, average);
inputFile.close();
output.close();
}
}
我的异常类:
package chapter11_homework;
public class InvalidStringException extends Exception{
public InvalidStringException(String msg){
super(msg);
}
}
答案 0 :(得分:0)
您调用了calcWage
方法,但是对它返回的值没有做任何事情。您可以将该值存储在变量中,然后打印该变量:
double wage = calcWage(sum, hourRate);
JOptionPane.showMessageDialog(null, String.format("Amount paid should be: $%.2f\n",wage));
或者您可以直接打印方法返回的值:
JOptionPane.showMessageDialog(null, String.format("Amount paid should be: $%.2f\n",calcWage(sum, hourRate)));