简体   繁体   English

从输入文件中读取然后按升序打印排序的名字

[英]reading from input file then printed sorted firstname in ascending order

import static java.lang.System.*;
import java.io.FileNotFoundException;
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Comparator.comparing;


public class Main
{
  public static void main (String[]args) throws IOException
  {
      
    PrintWriter pw1 = new PrintWriter ("input.txt");
      pw1.println ("Mickey Mouse CS 98.7 67.8 23.5");
      pw1.println ("Minnie Mouse ENG 45.6 98.3 94.7");
      pw1.println ("Donald Duck NET 56.8 74.2 78.4");
      pw1.println ("Bob Builder CS 78.5 89.4 82.5");
      pw1.println ("Snow White MAT 56.6 32.4 56.6");
      pw1.println ("Hellen Keller CHEM 78.8 23.1 99.6");
      pw1.println ("Daffy Duck ENG 67.4 55.5 89.5");
      pw1.println ("Fred Flinstone MAT 45.3 87.4 38.9");
      pw1.println ("Daffy Duck CS 76.5 22.2 88.5");
      pw1.println ("Bugs Bunny NET 68.4 89.7 95.6");
      pw1.println ("Winnie Pooh CHEM 77.5 89.4 98.2");
      pw1.close ();
File q=new File("input.txt");
generateStatsFile(q);
}

public static void generateStatsFile (File inputfile) throws IOException{
    Scanner in=new Scanner (inputfile);
    ArrayList<student> ss=new ArrayList<student>(4);
    ArrayList<student>s=new ArrayList<student>();
     String []fname=new String[s.size()];
    while (in.hasNext()){
        student we=new student(in.next (), in.next (), in.next(),in.nextFloat (),
        in.nextFloat (), in.nextFloat ());
        ss.add(we);
        
        
      
        //Collections.sort(s);
        
    }
        FileWriter of=new FileWriter("out.txt");
    PrintWriter output=new PrintWriter(of);
    while(in.hasNext()){
        student ee=new student(in.next (), in.next (), in.next(),in.nextFloat (),
        in.nextFloat (), in.nextFloat ());
    s.add(ee);    
        
        
    }
    
    //Collections.sort(s, comparing(ee::getfname));
/*s.sort((o1,o2)
-> o1.getfname().compareTo(
                          o2.getfname()));*/
                          
  // Comparator<student> compareByName = (student o1, student o2) ->
                //  o1.getfname().compareTo( o2.getfname() );
    
//Collections.sort(s,compareByName);


    for (student he:ss)
    {
        
        
        
       
        output.printf("%s %s %.1f%n",he.getfname(),he.getlname(),he.getavg(he.getg1(),he.getg2(),he.getg3()));


        
    }
 String []cnmb=(s.toArray(new String[s.size()])); 
 Arrays.sort(cnmb);
output.print(cnmb);    
    
    
   /* for(int i=0;i<s.size();i++){
    System.out.println(Arrays.toString(s.toArray()));    
        
        
    }*/
    for(String ha:cnmb){
    out.println(ha);
    
} 


/*for (String ha:s){
    
    String [] fn=new String[s.size()];
   for(int i=0;i<s.size();i++){
    fn[i]=ha.getfname();
    
}*/
//out.print(fn); 
    
    
    //out.print(s);
    

         
    in.close();
    output.close();
  
  
 
}
}

Hi so basically this method is supposed to write to an output file a.the avg grade and letter b.firstname sorted in ascending order你好所以基本上这个方法应该写入一个 output 文件 a.平均成绩和字母 b.名字按升序排序

the first options worked.第一个选项奏效了。 however, the code I wrote for option b is not working it's either not printing out anything or just prints something like [Ljava.lang.String;@880ec60 into the file can someone please help I know the code is really messed because I put a lot of comment signs before different lines of code but perhaps some of them are supposed to be useful I'm just not getting the full code working right.但是,我为选项 b 编写的代码无法正常工作,它要么不打印任何内容,要么只是在文件中打印类似[Ljava.lang.String;@880ec60的内容,有人可以帮忙吗?我知道代码真的很乱,因为我放了一个在不同的代码行之前有很多注释符号,但也许其中一些应该有用我只是没有让完整的代码正常工作。

public class student implements Comparable<student>{
       
private String fname;
private String lname;
private String major;
private float grades1;    
private float grades2; 
private float grades3;   

public String getfname() {return fname;}
public String getlname() {return lname;}
private String getmajor() {return major;}
public float getg1() {return grades1;}
public float getg2() {return grades2;}
public float getg3() {return grades3;}

@Override
    public int compareTo(student e) {
        return this.getfname().compareTo(e.getfname());
    }

public student(){
    
    
    
}
public String fname(){
return fname;    
    
    
    
}
public student(String f){
fname=f;    
    
    
}
public student(String f,String l,String m,float g1,float g2, float g3)  {  
    fname=f;
    lname=l;
    major=m;
    grades1=g1;
    grades2=g2;
    grades3=g3;
     
}
public student(String f,String l,float g1,float g2, float g3)  {  
    fname=f;
    lname=l;
    grades1=g1;
    grades2=g2;
    grades3=g3;
     
}
public float getavg (float g1,float g2,float g3){
grades1=g1;
grades2=g2;
grades3=g3;

float avg=(g1+g2+g3)/3;
    
    
return avg;   
}

public String [] sortfname(String fname){
String [] f=new String[0];


return f;

}





You seem to be making this a lot more complicated than it needs to be.您似乎使这比需要的复杂得多。

Your student class already implements Comparable interface so you don't need class Arrays , you can use method sort in class java.util.Collections .您的student class 已经实现了Comparable接口,因此您不需要 class Arrays ,您可以使用 class java.util.Collections中的方法排序

Also, class java.io.PrintWriter has a constructor that takes a String argument so no need to create a FileWriter .此外, class java.io.PrintWriter具有一个采用String参数的构造函数,因此无需创建FileWriter

Note that files need to be closed, hence, in the below code, I use try-with-resources .请注意,文件需要关闭,因此,在下面的代码中,我使用了 try-with-resources

For the purposes of your program, you only need one constructor for class student .出于您的程序的目的,您只需要一个 class student的构造函数。

In order to get correct output, you need to override method toString .为了获得正确的 output,您需要重写方法toString

Method getAverage should not have any parameters.方法getAverage不应有任何参数。 It should use the class members grades1 , grades2 and grades3 which should have been initialized in the class constructor.它应该使用应该在 class 构造函数中初始化的 class 成员grades1grades2grades3

You mention letter grades in your question but I see nothing in your code that deals with that so I added method getLetterGrade to class student .您在问题中提到了字母等级,但我在您的代码中看不到任何处理该问题的内容,因此我将方法getLetterGrade添加到 class student

In the below code, I create a List of student objects - rather than writing them to a file and then recreating the List by reading the file.在下面的代码中,我创建了一个student对象List ——而不是将它们写入文件,然后通过读取文件重新创建List

Lastly, you should consider using java naming conventions .最后,您应该考虑使用java 命名约定 According to those conventions, the class name is changed in the below code to Student .根据这些约定,名称 class 在以下代码中更改为Student

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Student implements Comparable<Student> {
    private String fname;
    private String lname;
    private String major;
    private float grades1;
    private float grades2;
    private float grades3;

    public Student(String fname,
                   String lname,
                   String major,
                   float grades1,
                   float grades2,
                   float grades3) {
        this.fname = fname;
        this.lname = lname;
        this.major = major;
        this.grades1 = grades1;
        this.grades2 = grades2;
        this.grades3 = grades3;
    }

    @Override
    public int compareTo(Student o) {
        return fname.compareTo(o.fname);
    }

    public float getAverage() {
        float total = grades1 + grades2 + grades3;
        return total / 3;
    }

    public char getLetterGrade() {
        char letter;
        float average = getAverage();
        if (average >= 90.0f  &&  average <= 100.0f) {
            letter = 'A';
        }
        else if (average >= 80.0f  &&  average < 90.0f) {
            letter = 'B';
        }
        else if (average >= 70.0f  &&  average < 80.0f) {
            letter = 'C';
        }
        else if (average >= 60.0f  &&  average < 70.0f) {
            letter = 'D';
        }
        else if (average >= 0.0f  &&  average < 60.0f) {
            letter = 'F';
        }
        else {
            throw new RuntimeException("Invalid average: " + average);
        }
        return letter;
    }

    public String toString() {
        return String.format("%s %s %s %.2f %c", fname, lname, major, getAverage(), getLetterGrade());
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("Mickey", "Mouse", "CS", 98.7f, 67.8f, 23.5f));
        list.add(new Student("Minnie", "Mouse", "ENG", 45.6f, 98.3f, 94.7f));
        list.add(new Student("Donald", "Duck", "NET", 56.8f, 74.2f, 78.4f));
        list.add(new Student("Bob", "Builder", "CS", 78.5f, 89.4f, 82.5f));
        list.add(new Student("Snow", "White", "MAT", 56.6f, 32.4f, 56.6f));
        list.add(new Student("Hellen", "Keller", "CHEM", 78.8f, 23.1f, 99.6f));
        list.add(new Student("Daffy", "Duck", "ENG", 67.4f, 55.5f, 89.5f));
        list.add(new Student("Fred", "Flinstone", "MAT", 45.3f, 87.4f, 38.9f));
        list.add(new Student("Daisy", "Duck", "CS", 76.5f, 22.2f, 88.5f));
        list.add(new Student("Bugs", "Bunny", "NET", 68.4f, 89.7f, 95.6f));
        list.add(new Student("Winnie", "Pooh", "CHEM", 77.5f, 89.4f, 98.2f));
        Collections.sort(list);
        try (PrintWriter pw = new PrintWriter("out.txt")) {
            for (Student learner : list) {
                pw.println(learner);
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

Here are the contents of file out.txt :以下是文件out.txt的内容:

Bob Builder CS 83.47 B
Bugs Bunny NET 84.57 B
Daffy Duck ENG 70.80 C
Daisy Duck CS 62.40 D
Donald Duck NET 69.80 D
Fred Flinstone MAT 57.20 F
Hellen Keller CHEM 67.17 D
Mickey Mouse CS 63.33 D
Minnie Mouse ENG 79.53 C
Snow White MAT 48.53 F
Winnie Pooh CHEM 88.37 B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 2 个文件读取输入并按升序写入第三个文件 - Reading input from 2 files and writing to a third file in ascending order 升序排序数组是按降序打印的吗? - Ascending order Sorted array is getting printed in descending order? 从要打印的文件中读取布尔值 - reading boolean value from a file to be printed 给定一个整数数组作为输入,如果该数组已排序,则返回true。 请注意,数组可以按升序或降序排序 - Given an array of integers as input, return true if the array is sorted. Note that the array can be sorted in either ascending or descending order 在 java 中按升序合并 2 个排序数组 - Merge 2 sorted array in Ascending order in java 从Java文本文件中读取的升序字母 - Order letters in ascending order read in from a text file in Java Java快速排序,从用户输入文件读取到任何数组(待排序) - Java quick sort, reading from a user input file into any array (to be sorted) 升序排序文件输出 - sorting file ouput in ascending order 以升序读取和写入文本文件。 (小/烦人的错误-即将完成) - Reading and writing a text file in ascending order. ( Small/annoying error- nearly completed) Arrays.BinarySearch是否要求数组按升序排序 - Does Arrays.BinarySearch require that the array is sorted in ascending order
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM