简体   繁体   中英

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

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.

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 .

Also, class java.io.PrintWriter has a constructor that takes a String argument so no need to create a FileWriter .

Note that files need to be closed, hence, in the below code, I use try-with-resources .

For the purposes of your program, you only need one constructor for class student .

In order to get correct output, you need to override method toString .

Method getAverage should not have any parameters. It should use the class members grades1 , grades2 and grades3 which should have been initialized in the class constructor.

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 .

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.

Lastly, you should consider using java naming conventions . According to those conventions, the class name is changed in the below code to 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM