【问题标题】:Creating Constructor Methods创建构造方法
【发布时间】:2015-12-07 03:31:00
【问题描述】:

有一个班级计划,我正在与多个班级一起工作。在 classroll 类中,我有一个构造方法“ClassRoll (String f) {”,假设 ....

从输入文件 f 中读取班级卷数据,为每个学生创建学生对象并将它们添加到学生的 ArrayList 中。 输入文件的第一行包含课程标题。每个学生的数据显示在一个单独的行中,由名字、姓氏、score1、score 2 和 score3 组成,至少用一个空格分隔。

下面我将展示 classroll 类和我尝试调用该构造函数的主要方法。每次我运行程序时,我都会收到来自该构造函数的错误。我需要有关如何正确创建该构造函数来完成它需要做的事情的帮助,因为我的尝试不起作用。任何帮助都将不胜感激,谢谢。

public class ClassRoll {

private ArrayList<Student> students = new ArrayList<Student>();
private String title;
private String filename = "data.txt";


 ClassRoll(String f) {      
    Scanner kb = new Scanner(System.in);
    String inpFileName = kb.next();
    File inpFile = new File(inpFileName);

    boolean firstline = true;
    while(kb.hasNextLine()){
        if(firstline){
            title = kb.nextLine();
            firstline = false;
        }
        else{
            String fName = kb.nextLine();
            String lName = kb.nextLine();
            int score1 = kb.nextInt();
            int score2 = kb.nextInt();
            int score3 = kb.nextInt();

            students.add(new Student(fName, lName));

        }
    }


}


void Remove() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

    Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0) {
            students.remove(i);

        } else {
            System.out.println("Error: Student is not in Class");
        }

    }

}

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()));


}

void Add() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

    System.out.println("What is the Student's first score?");
    int score1 = kb.nextInt();

    System.out.println("What is the Student's second score?");
    int score2 = kb.nextInt();

    System.out.println("What is the Student's third score?");
    int score3 = kb.nextInt();

    Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0) {
            System.out.println("Student already in class");
        } else {
            students.add(s);
        }
    }
}

void changeScore1() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

    System.out.println("What is the Student's first score?");
    int score1 = kb.nextInt();

    Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0) {
            s.setScore1(i);
        } else {
            System.out.println("Error: Student is not in Class");
        }

    }

}

void changeScore2() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

    System.out.println("What is the Student's first score?");
    int score1 = kb.nextInt();

    Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0) {
            s.setScore2(i);
        } else {
            System.out.println("Error: Student is not in Class");
        }

    }

}

void changeScore3() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

    System.out.println("What is the Student's first score?");
    int score1 = kb.nextInt();

    Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0) {
            s.setScore3(i);
        } else {
            System.out.println("Error: Student is not in Class");
        }

    }

}

public void find() {
    Scanner kb = new Scanner(System.in);

    System.out.println("What is the Student's first name?");
    String fName = kb.next();

    System.out.println("What is the Student's last name?");
    String lName = kb.next();

     Student s = new Student(fName, lName);

    for (int i = 0; i < students.size(); i++) {
        if (s.compareTo(students.get(i)) == 0){
            System.out.println(s);
        }
    }
}

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 sortNames() {
    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 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 Assignment4 {

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(fileName);


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

    while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit"))) {
        if (!(ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("Add")
                || ans.equalsIgnoreCase("s")|| 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 'a':
                    c.Add();
                    break;
                case 's':
                    c.sortAverage();
                    c.Display();
                    break;
                case 'n':
                    c.sortNames();
                    c.Display();
                    break;
                case 'r':
                    c.Remove();
                    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("a or Add to add a student in the classroll");

    System.out.println("sa or average to sort the students based on their average");

    System.out.println("sn 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");
}

}

学生班

public class Student {

private String fName;

private String lName;

private Exams scores;

Student(String fn, String ln) {
    fName = fn;
    lName = ln;
    scores = new Exams();

}

public void setScore1(int sc) {
    int score1 = 0;
    score1 = sc;

}

public void setScore2(int sc) {
    int score2 = 0;
    score2 = sc;

}

public void setScore3(int sc) {
    int score3 = 0;
    score3 = sc;

}

public String toSring() {
    return String.format("%-10s %-10s %4.2f\n", fName, lName, scores);
}

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

public int compareTo(Student s) {
    String name1 = lName + "  " + fName;
    String name2 = s.lName + "  " + s.fName;

    if((lName + "  " + fName).compareTo(s.lName + "  " + s.fName)> 0)
        return 1;
    else if ((lName + "  " + fName).compareTo(s.lName + "  " + s.fName)< 0)
        return -1;
    else return 0;
}
}

【问题讨论】:

  • 请分享错误信息和学生班级
  • @Ahmed 我添加了学生班级
  • @Ahmed 异常在 java.util.Scanner.throwFor(Scanner.java:864) 在 java.util.Scanner.next(Scanner.java:1485) 线程“主”java.util.InputMismatchException ) 在 java.util.Scanner.nextInt(Scanner.java:2117) 在 java.util.Scanner.nextInt(Scanner.java:2076) 在 classroll.ClassRoll.(ClassRoll.java:41) 在 classroll.Assignment4 .main(Assignment4.java:23)
  • 您在读取未创建对象的文件时遇到异常。字符串 fName = kb.nextLine();字符串 lName = kb.nextLine(); int score1 = kb.nextInt(); int score2 = kb.nextInt(); int score3 = kb.nextInt();
  • @Ahmed 问题出在构造函数类中正确吗?这是我遇到的问题,我试图让它读取文件的方式不起作用

标签: java file methods constructor


【解决方案1】:

这个异常是由 Scanner 抛出的

由 Scanner 抛出以指示检索到的令牌不 匹配预期类型的​​模式,或者令牌不在 预期类型的​​范围。

请检查您的输入文件。它会解决你的问题。

您的数据必须是行分隔的。

代码sn-ps

Scanner kb = new Scanner(new FileInputStream(new File("d://app//test.txt")));
boolean firstline = true;
        while(kb.hasNext()) {
            if (firstline) {
                title = kb.nextLine();
                firstline = false;
            } else {
                String fName =kb.next() ;
                String lName = kb.next();
                int score1 = kb.nextInt();
                int score2 = kb.nextInt();
                int score3 = kb.nextInt();

                students.add(new Student(fName, lName));
            }
        }

【讨论】:

  • 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
  • 就是这个文件。并检查输入文件在哪里?对不起,我是一个初级程序员
  • 您的文件在一行中有空格或在新行中。另外,您的扫描仪对象不是指文件。
  • 那我该怎么办?我知道我从文件中读取的内容不正确,但这就是为什么我发布了我试图自己解决但我不知道如何正确解决的问题
  • 你知道我可以改变什么吗?所以它可以正确读取文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多