2

I've been trying to find the answer to this and can't seem to find it. I'm supposed to read a text file with student names and grades and find the lowest and highest grade. This is how far I've come. I'm able to find the highest and lowest grade. I can also find the name of the student with the highest grade but I cannot get the name of the one that has the lowest grade.

    File ft = new File("Grades.txt");
    Scanner scan = new Scanner(ft);
    String names = "";
    String beststudent = "";
    String worsestudent = "";
do {
        names = scan.next();
        largest = parseInt(String.valueOf(scan.next()));
        smallest = largest;
        if (largestNumber > largest) {
            worsestudent = names;
        }
        if (largestNumber < largest) {
            smallestNumber = largestNumber;
            largestNumber = largest;
            beststudent = names;
        }    

    } while (scan.hasNext());

}

The format of names are NAME_LASTNAME INTEGER in my text file if you were wondering.

2 Answers2

1

Here is a simple way of doing it.

  • intialize smallestNumber to Integer.MAX_VALUE;
  • intialize largestNumber to Integer.MIN_VALUE;
  • read in name and number.
  • if smallestNumber is less than number, assign it to smallestNumber and save worstName
  • else it must be larger or equal so just assign it to largestNumber and save bestName -continue back to reading in names and numbers.
WJS
  • 22,083
  • 3
  • 14
  • 32
-1

I made you this little algorithm you can try it

import java.util.ArrayList;
import java.util.List;

public class example {
    static int a,z;
    public static void main(final String args[]){
        final List<Integer> students = new ArrayList<Integer>(); 
        students.add(20);
        students.add(100);
        students.add(50);

        System.out.println(students);
        a = students.get(0);
        z = a;
        students.forEach(current -> {
            if (current > a) {
                a = current;
            }
            if (current < z) {
                z=current;    
            }    
        });
        System.out.println("Best grade: "+a);
        System.out.println("Worse grade: "+z);
    }
}

Of course only the if sentences you will found useful. i just made the whole thing to try it before answering haha

420root
  • 53
  • 7