使用一个ArrayList来创建菜单,并使用文本文件作为输入(使用BufferedReader)

huangapple go评论58阅读模式
英文:

Using an arrayList to create a menu and using a text file as input(bufferedReader)

问题

以下是您提供的代码的翻译部分:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        try {
            BufferedReader br = new BufferedReader(new FileReader("c://student.txt"));
            char g;
            int yl, i; // Added missing variable declaration "i"
            String ln, fn, id, cors, con; // Changed "con" to "cors"
            Student v[] = new Student[4];
            Scanner sc = new Scanner(System.in);
            boolean en = true;
            boolean ent = true;

            for (i = 0; i < 4; i++) {
                id = br.readLine();
                ln = br.readLine();
                fn = br.readLine();
                g = br.readLine().charAt(0);
                cors = br.readLine();
                yl = Integer.parseInt(br.readLine());

                v[i] = new Student(ln, fn, id, cors, g, yl);
            }

            while (en == true) {
                System.out.println("--------------------------------------");
                System.out.println("--------------------------------------");
                System.out.println("1. Name");
                System.out.println("2. Course then Name");
                System.out.println("3. Year Level then Name");
                System.out.println("4. Course then Year Level and the Name");
                System.out.println("5. Exit");
                System.out.println("--------------------------------------");
                System.out.println("--------------------------------------");
                System.out.println("Choose Menu: ");
                int choice = sc.nextInt();
                switch (choice) {
                    case 1:
                        Arrays.sort(v);
                        display_array(v);
                        break;
                    case 2:
                        Arrays.sort(v);
                        display_array(v);
                        break;
                    case 3:
                        Arrays.sort(v);
                        display_array(v);
                        break;
                    case 4:
                        Arrays.sort(v);
                        display_array(v);
                        break;
                    case 5:
                        en = false;
                        System.out.println("\n\n \nTHANK YOU FOR USING THE PROGRAM!!");
                        break;
                }
                if (en != false) {
                    System.out.println("Press [Enter key] to continue");
                    try {
                        System.in.read();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
    }

    public static void display_array(Student arr_v[]) throws IOException {
        System.out.println("--------------------------------------");
        for (int i = 0; i < arr_v.length; i++) {
            arr_v[i].display();
        }
        System.out.println("--------------------------------------");
    }
}
public class Student implements Comparable {
    private String lastname, firstname, studentid, course;
    private char gender;
    private int yearlevel;

    public Student(String ln, String fn, String id, String cors, char g, int yl) {
        lastname = ln;
        firstname = fn;
        studentid = id;
        course = cors;
        gender = g;
        yearlevel = yl;
    }

    public int compareTo(Object anotherObject) {
        Student anotherStudent = (Student) anotherObject;
        int compareResult = this.course.compareTo(anotherStudent.lastname);
        if (compareResult == 0) {
            return this.firstname.compareTo(anotherStudent.firstname);
        }
        return compareResult;
    }

    public void display() {
        System.out.printf("ID: %-8s  Name: %-20s  Sex: %c  Course: %-8s  Year: %d\n",
                studentid, (lastname + ", " + firstname), gender, course, yearlevel);
    }

    // Getter and setter methods...
}
英文:

As you can see below I tried creating a switch case for choices
1. Name
2. Course then Name
3. Year Level then Name
4. Course then Year Level and the Name
5. Exit
I don't know how to use switch case so that I could sort everything according to the menu. I will be using comparable and I am only allowed to edit the method called compareTo. My mind is blank and I got no idea where to start.
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2

These are the inputs from text file

    import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader(&quot;c://student.txt&quot;));
char g;
int yl, I;
String ln, fn, id, cors, con;
Student v[] = new Student[4];
Scanner sc= new Scanner(System.in);
boolean en = true;
boolean ent = true;
for(i = 0; i &lt; 4; i++){
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
v[i] = new Student(ln, fn, id, cors, g, yl);
}
while(en == true){
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;1. Name&quot;);
System.out.println(&quot;2. Course then Name&quot;);
System.out.println(&quot;3. Year Level then Name&quot;);
System.out.println(&quot;4. Course then Year Level and the Name&quot;);
System.out.println(&quot;5. Exit&quot;);
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;Choose Menu: &quot;);
int choice = sc.nextInt();
switch(choice){
case 1 :
Arrays.sort(v);
display_array(v);
break;
case 2 :
Arrays.sort(v);
display_array(v);
break;
case 3 :
Arrays.sort(v);
display_array(v);
break;
case 4 :
Arrays.sort(v);
display_array(v);
break;
case 5 :
en = false;
System.out.println(&quot;\n\n \nTHANK YOU FOR USING THE PROGRAM!!&quot;);
break;
}
if(en != false){
System.out.println(&quot;Press [Enter key] to continue&quot;);
try{
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
System.err.println(&quot;File not found&quot;);
} catch (IOException e) {
System.err.println(&quot;Unable to read the file.&quot;);
}
}
public static void display_array(Student arr_v[]) throws IOException{
System.out.println(&quot;--------------------------------------&quot;);
for(int i = 0; i &lt; arr_v.length; i++){
arr_v[i].display();
}
System.out.println(&quot;--------------------------------------&quot;);
}
}```
```
public class Student implements Comparable {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String ln, String fn, String id, String cors, char g, int yl) {
lastname = ln;
firstname = fn;
studentid = id;
course = cors;
gender = g;
yearlevel = yl;
}
public int compareTo(Object anotherObject) {
Student anotherStudent = (Student) anotherObject;
int compareResult =         
this.course.compareTo(anotherStudent.lastname); 
if(compare )
return 0;  
}
public void display() {
System.out.printf(&quot;ID: %-8s  Name: %-20s  Sex: %c  Course: %-8s  Year: %d\n&quot;, studentid, (lastname + &quot;, &quot; + firstname), gender, course, yearlevel );
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
}```
</details>
# 答案1
**得分**: 0
所有程序员都需要学会如何调试他们的代码。如果你正在使用集成开发环境(IDE),我建议你学习如何使用它的调试器。
在下面的代码中,你有一些不需要的`readLine()`方法调用。在下面的代码中,我已经将这些行标记为注释。我还将`display_array()`和`main()`方法整合到了`Student`类中,只是为了让所有内容都在一个类中,但你不一定非要这样做。
```java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Student {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String id, String ln, String fn, char g, String cors, int yl) {
studentid = id;
lastname = ln;
firstname = fn;
gender = g;
course = cors;
yearlevel = yl;
}
private static void display_array(Student[] v) {
for (Student s : v) {
s.display();
}
}
public void display() {
System.out.println("Name      : " + lastname + ", " + firstname);
System.out.println("Student ID: " + studentid);
System.out.println("Course    : " + course);
System.out.println("Gender    : " + gender);
System.out.println("Year Level: " + yearlevel);
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\student.txt"));) {
char g;
int yl;
int i;
String ln;
String fn;
String id;
String cors;
Student v[] = new Student[Integer.parseInt(br.readLine())];
//            br.readLine();
for (i = 0; i < v.length; i++) {
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
//                g = (char) br.read();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
//                if ((br.readLine()) != null)
//                    br.readLine();
v[i] = new Student(id, ln, fn, g, cors, yl);
}
display_array(v);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}

我还修改了student.txt文件。根据你的代码,文件的第一行应该是文件中学生的数量。在你的问题中的示例文件中,有四名学生。

4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
英文:

All programmers need to learn how to debug their code. If you are using an IDE then I recommend that you learn how to use its debugger.

You have some calls to method readLine() that you do not need. In the below code, I have marked these lines as comments. I also incorporated the methods display_array() and main() into class Student just so everything would be in the one class, but you don't have to do that.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Student {
    private String lastname, firstname, studentid, course;
    private char gender;
    private int yearlevel;

    public Student(String id, String ln, String fn, char g, String cors, int yl) {
        studentid = id;
        lastname = ln;
        firstname = fn;
        gender = g;
        course = cors;
        yearlevel = yl;
    }

    private static void display_array(Student[] v) {
        for (Student s : v) {
            s.display();
        }
    }

    public void display() {
        System.out.println(&quot;Name      : &quot; + lastname + &quot;, &quot; + firstname);
        System.out.println(&quot;Student ID: &quot; + studentid);
        System.out.println(&quot;Course    : &quot; + course);
        System.out.println(&quot;Gender    : &quot; + gender);
        System.out.println(&quot;Year Level: &quot; + yearlevel);
    }

    public void setGender(char gender){
        this.gender = gender;
    }

    public char getGender(){
        return gender;
    }

    public void setLastname(String lastname){
        this.lastname = lastname;
    }

    public String getLastname(){
        return lastname;
    }

    public void setFirstname(String firstname){
        this.firstname = firstname;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setStudentId(String studentid){
        this.studentid = studentid;
    }

    public String getStudentId(){
        return studentid;
    }

    public void setCourse(String course){
        this.course = course;
    }

    public String getCourse(){
        return course;
    }

    public void setYearLevel(int yearlevel){
        this.yearlevel = yearlevel;
    }

    public int getYearLevel(){
        return yearlevel;
    }

    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader(&quot;c:\\student.txt&quot;));) {
            char g;
            int yl;
            int i;
            String ln;
            String fn;
            String id;
            String cors;
            Student v[] = new Student[Integer.parseInt(br.readLine())];
//            br.readLine();
            for (i = 0; i &lt; v.length; i++) {
                id = br.readLine();
                ln = br.readLine();
                fn = br.readLine();
//                g = (char) br.read();
                g = br.readLine().charAt(0);
                cors = br.readLine();
                yl = Integer.parseInt(br.readLine());
//                if ((br.readLine()) != null)
//                    br.readLine();

                v[i] = new Student(id, ln, fn, g, cors, yl);
            }
            display_array(v);
        }
        catch (FileNotFoundException e) {
            System.err.println(&quot;File not found&quot;);
        }
        catch (IOException e) {
            System.err.println(&quot;Unable to read the file.&quot;);
        }
    }
}

I also changed file student.txt. According to your code, the first line of the file needs to be the number of students in the file. In the sample file in your question, there are four students.

4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2

答案2

得分: 0

public final class Student {

    private final String id;
    private final String firstName;
    private final String lastName;
    private final char gender;
    private final String course;
    private final int yearLevel;

    public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = Character.toUpperCase(gender);
        this.course = course;
        this.yearLevel = yearLevel;
    }

    public void display(PrintStream out) {
        out.format("姓名         : %s, %s\n", lastName, firstName);
        out.format("学生编号     : %s\n", id);
        out.format("课程         : %s\n", course);
        out.format("性别         : %s\n", gender);
        out.format("年级         : %d\n", yearLevel);
    }

}

public static void main(String... args) throws FileNotFoundException {
    File file = new File("c://student.txt");
    List<Student> students = readStudents(file);
    display(students);
}

private static List<Student> readStudents(File file) throws FileNotFoundException {
    try (Scanner scan = new Scanner(file)) {
        List<Student> students = new ArrayList<>();

        while (scan.hasNext()) {
            String id = scan.next();
            String lastName = scan.next();
            String firstName = scan.next();
            char gender = scan.next().charAt(0);
            String course = scan.next();
            int yearLevel = scan.nextInt();
            students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
        }

        return students;
    }
}

private static void display(List<Student> students) {
    System.out.println("--------------------------------------");
    System.out.println("--------------------------------------");
    System.out.println("1. 姓名");
    System.out.println("2. 课程再加姓名");
    System.out.println("3. 年级再加姓名");
    System.out.println("4. 课程再加年级和姓名");
    System.out.println("5. 退出");
    System.out.println("--------------------------------------");
    System.out.println("--------------------------------------");

    students.forEach(student -> {
        student.display(System.out);
        System.out.println();
    });
}
英文:
public final class Student {
private final String id;
private final String firstName;
private final String lastName;
private final char gender;
private final String course;
private final int yearLevel;
public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = Character.toUpperCase(gender);
this.course = course;
this.yearLevel = yearLevel;
}
public void display(PrintStream out) {
out.format(&quot;Name       : %s, %s\n&quot;, lastName, firstName);
out.format(&quot;Student ID : %s\n&quot;, id);
out.format(&quot;Course     : %s\n&quot;, course);
out.format(&quot;Gender     : %s\n&quot;, gender);
out.format(&quot;Year Level : %d\n&quot;, yearLevel);
}
}
public static void main(String... args) throws FileNotFoundException {
File file = new File(&quot;c://student.txt&quot;);
List&lt;Student&gt; students = readStudents(file);
display(students);
}
private static List&lt;Student&gt; readStudents(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
List&lt;Student&gt; students = new ArrayList&lt;&gt;();
while (scan.hasNext()) {
String id = scan.next();
String lastName = scan.next();
String firstName = scan.next();
char gender = scan.next().charAt(0);
String course = scan.next();
int yearLevel = scan.nextInt();
students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
}
return students;
}
}
private static void display(List&lt;Student&gt; students) {
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;1. Name&quot;);
System.out.println(&quot;2. Course then Name&quot;);
System.out.println(&quot;3. Year Level then Name&quot;);
System.out.println(&quot;4. Course then Year Level and the Name&quot;);
System.out.println(&quot;5. Exit&quot;);
System.out.println(&quot;--------------------------------------&quot;);
System.out.println(&quot;--------------------------------------&quot;);
students.forEach(student -&gt; {
student.display(System.out);
System.out.println();
});
}

huangapple
  • 本文由 发表于 2020年10月1日 14:34:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64150207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定