java - 构造函数 ClassRoll(String f) 赋值帮助,我需要确定为什么无法显示滚动

标签 java arrays string class constructor

所以,基本上我有一个作业,要求我编写一个 java 程序来帮助维护类(class)。该程序必须包含四个类(class):Student、Exams、ClassRoll 和Assignment4(Main)。 我已经开发了所有类,但 ClassRoll 构造函数无法正确执行。当我运行程序时,系统会提示我输入文件名选项,一旦我输入文件名,我会看到 null,然后是修改和/或显示列表的选项,但是当我输入命令时,它不起作用,它给了我一个错误。 输出应该是

     Expected input/output:
     Assuming that the file data.txt contains:

     COP2210

     John Doe          50 60 70
     Marco Boyle       50 60 73
     Eric Munzon      45 100 90
     Marry Able       95 100 100
     Jack Smith      100 100 100
     Elizabeth Gomez 100 100 100

     The following is a sample input output run:

     What is the name of input file: data.txt

     Enter one of the following commands

     a or add to add a student in the class roll
     sa or average to sort the students based on their average
     sn or names to sort the students based on their last names
     r or remove to remove a student from the class roll
     s or save to save the list of students back to the datafile

这是我的类(class);

     public class Student {
     private String fName = "";
     private String lName = "";
     private Exam scores;


     public Student(String f, String l){
        fName=f;
        lName=l;
        scores = new Exam();

     }

     public void setScore1(int score) {
        scores.setScore1(score);
     }

     public void setScore2(int score) {
        scores.setScore2(score);
     }

     public void setScore3(int score) {
        scores.setScore3(score);
     }

     public String toString() {
     return lName + "\t" + fName + "\t" +
        scores.toString();
     }

     public double getAverage() {
        return (scores.getScore1() + scores.getScore2() +         
        scores.getScore3())/3.0;
     }

     public boolean equals(String f, String l) {
        return f.equals(fName) && l.equals(lName);
     }

     public int compareTo(Student s){
        if (lName.compareTo(s.lName) > 0)
         return 1;
        else if (lName.compareTo(s.lName) < 0)
         return -1;
        else if (fName.compareTo(s.fName) > 0)
         return 1;
        else if (fName.compareTo(s.fName) < 0)
         return -1;
        else return 0;
     }}

     public class Exam {

     private int score1;
     private int score2;
     private int score3;

     public Exam(){
        score1=0;
        score2=0;
        score3=0;   
     }

     public void setScore1(int score) {
        score1=score;
     }

     public int getScore1() {
        return score1;
     }

     public void setScore2(int score) {
        score2=score;
     }

     public int getScore2() {
        return score2;
     }

     public void setScore3(int score) {
        score3=score;
     }

     public int getScore3() {
        return score3;
     }

     public String toString() {
        return Integer.toString(score1) + "\t"  
           +Integer.toString(score2)
           + "\t" + Integer.toString(score3) + "\t";
     }}

     public class ClassRoll {

     ArrayList students = new ArrayList();
     String title;
     String fileName;



     public  ClassRoll(String f) throws IOException {

     Scanner fileScan, lineScan;
     String line;
     fileName = f;
     fileScan = new Scanner(new File(f));
     title = fileScan.nextLine();
     System.out.println("Title =" + title);

     while (fileScan.hasNext()) {
        line = fileScan.nextLine();
        lineScan = new Scanner(line);
        lineScan.useDelimiter("\t");
        String lastName = lineScan.next();
        String firstName = lineScan.next();
        Student s = new Student(firstName, lastName);
        s.setScore1(lineScan.nextInt());
        s.setScore2(lineScan.nextInt());
        s.setScore3(lineScan.nextInt());
        students.add(s);
        //display(students);
        ClassRoll c = new ClassRoll();
        c.display();
     }
     }


     void display() {

        DecimalFormat fmt = new DecimalFormat("0.00");
        System.out.println("\t\t\t" + title);

        double classAverage = 0.0;

        for (int i = 0; i < students.size(); i++) {
          Student s = (Student) students.get(i);
          System.out.print(s.toString());
          System.out.println("\t" + fmt.format(s.getAverage()));
          classAverage = classAverage + s.getAverage();
        }
        System.out.println("\t\t\t" + fmt.format(classAverage /      
           students.size()));
        }

        public void insert() {

        Scanner input = new Scanner(System.in);
        System.out.print("First Name -> ");
        String firstName = input.next();
        System.out.print("Last Name -> ");
        String lastName = input.next();
        System.out.print("Score 1 -> ");
        int score1 = input.nextInt();
        System.out.print("Score 2 -> ");
        int score2 = input.nextInt();
        System.out.print("Score 3 -> ");
        int score3 = input.nextInt();
        Student s = new Student(firstName, lastName);
        s.setScore1(score1);
        s.setScore2(score2);
        s.setScore3(score3);
        students.add(s);
        }

        private int search(String f, String l) {
        int i = 0;
        while (i < students.size()) {
        Student s = (Student) students.get(i);
        if (s.equals(f, l)) {
            return i;
        } else {
          i++;
        }
        }
         return -1;
        }

        public Student find() {

         Scanner input = new Scanner(System.in);
         System.out.print("First Name -> ");
         String firstName = input.next();
         System.out.print("Last Name -> ");
         String lastName = input.next();

         int i = search(firstName, lastName);

         if (i >= 0) {
            return (Student) students.get(i);
         } else {
            return null;
         }}


         public void delete() {

           Scanner input = new Scanner(System.in);
           System.out.print("First Name -> ");
           String firstName = input.next();
           System.out.print("Last Name -> ");
    String lastName = input.next();

    int i = search(firstName, lastName);

    if (i >= 0) {
        students.remove(i);
    } else {
        System.out.println("Student not found");
    }
    }

    public void sortLastNames() {
       for (int i = 0; i < students.size() - 1; i++) {
       for (int j = i + 1; j < students.size(); j++) {
            Student s1 = (Student) students.get(i);
            Student s2 = (Student) students.get(j);
            if (s1.compareTo(s2) > 0) {
                students.set(i, s2);
                students.set(j, s1);
            }
        }
      }}

      public void sortAverage() {
        for (int i = 0; i < students.size() - 1; i++) {
        for (int j = i + 1; j < students.size(); j++) {
            Student s1 = (Student) students.get(i);
            Student s2 = (Student) students.get(j);
            if (s1.getAverage() < s2.getAverage()) {
                students.set(i, s2);
                students.set(j, s1);
            }
        }}}

    public void save() throws IOException {
    PrintWriter out = new PrintWriter(fileName);
    out.println(title);
    for (int i = 0; i < students.size(); i++) {
        Student s = (Student) students.get(i);
        out.println(s.toString());
    }
    out.close();

     }}

   public class Assignment4bis {


   public static void main(String[] args) throws IOException {       

    Scanner input=new Scanner(System.in);
    System.out.print("Enter the name of the input file ->");
    String fileName=input.next();

    ClassRoll c = new ClassRoll();
    c.display();

    prompt();
    System.out.print("Enter a command --> ");
    String ans=input.next();


  while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))       
  {
  if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
       ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
       ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
       ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
       ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
       ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
       System.out.println("Bad Command");
   else
       switch (ans.charAt(0))
        {
            case 'i':   c.insert();
                        break;
            case 'a':   c.sortAverage();
                        c.display();
                        break;
            case 'n':   c.sortLastNames();
                        c.display();
                        break;
            case 'r':   c.delete();
                        c.display();
                        break;
            case 'f':   Student s=c.find();
                        if (s == null)
                            System.out.println("Student not found");
                        else System.out.println(s.toString());
                        break;
            case 'd':   c.display();

                        break;
        }
        prompt();
        System.out.print("Enter a command --> ");
        ans=input.next();
    }
    c.save();
    System.out.println("Thank you for using this program");

    }

    public static void prompt(){
    System.out.println("Enter one of the following commands");
    System.out.println("i or insert to insert a student in the class  
       roll");
    System.out.println("a or average to sort the students based on 
       their average");
    System.out.println("n or names to sort the students based on their 
       last names");
    System.out.println("r or remove to remove a student from the class  
       roll");
    System.out.println("f or find to find a student in the class 
       roll");
    System.out.println("d or display to display the class roll");
    System.out.println("q or quit to exit the program");
    }}  

    Errors that I m still getting...

    run:
    Enter the name of the input file ->data.txt
    Title =COP2210
    Exception in thread "main" java.util.NoSuchElementException
     at java.util.Scanner.throwFor(Scanner.java:862)
     at java.util.Scanner.next(Scanner.java:1371)
     at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
     at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
    Java Result: 1

最佳答案

您的 ClassRoll“构造函数”是一个“伪构造函数”:

public class ClassRoll {
     ArrayList students = new ArrayList();
     String title;
     String fileName;

     public void ClassRoll(String f) throws IOException {

构造函数没有返回类型,因此去掉 void:

public class ClassRoll {
     ArrayList students = new ArrayList();
     String title;
     String fileName;

     public ClassRoll(String f) throws IOException {

作为一些侧面建议:

  • 您希望将用户界面与您的“模型”或逻辑类之一(ClassRoll)混合在一起,这是您可能不应该做的事情。我将保留所有用户界面代码,包括使用与 ClassRoll 分开的扫描仪和文件 I/O,这可能应该只包含创建集合的代码,以允许其他类在集合中添加或删除,并允许其他类用于查询集合的类。
  • 注意学习并遵守 Java 代码格式化规则。您与标准有一些偏差,包括让您的类声明行缩进与方法体和变量声明行相同、端大括号聚集在一起……这使得您的代码很难让其他 Java 程序员阅读和理解.

关于java - 构造函数 ClassRoll(String f) 赋值帮助,我需要确定为什么无法显示滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33838480/

相关文章:

java - String.intern() 线程安全有保证吗?

java - TPE 1105 用于 BulkRequestTransmissionStatus A2A IRS

Linux 的 Java 分析工具

java - HTTP 状态 500 - Servlet.init()

node.js - 更新数组中的对象或使用唯一字段插入数组

c++ - 这个变量赋值有什么不同?

java - 从 dv 摄像机进行实时 RTMP 流传输的最佳方式

java.nio.BufferOverflowException 构造 byte[]

arrays - VBA Redim 保留

javascript - 如何根据某些RegExp模式提取字符串的 "parts"?