How to find smallest value(from values given in a txt file) using BufferedReader in java

I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values. So far I have got two parts of the program but i'm not sure how to join them together.

import java.io.*;

class CalculateMin
{
    public static void main(String[] args)
    {
        try {
            BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
            int numberOfLines = 5;

            String[] textInfo = new String[numberOfLines];
            for (int i = 0; i < numberOfLines; i++) {
                textInfo[i] = br.readLine();
            }
            br.close();

        } catch (IOException ie) {
        }

    }
}

and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.

int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
    if (numArray[i] < smallestSoFar) {
        smallestSoFar = numArray[i];
    }
}

Appreciate your help

Answers


Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-

public static void main(String[] args) {
    try {
        BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
        String line;
        int lowestNumber = Integer.MAX_VALUE;
        int number;
        while ((line = br.readLine()) != null) {
            try {
                number = Integer.parseInt(line);
                lowestNumber = number < lowestNumber ? number : lowestNumber;
            } catch (NumberFormatException ex) {
                // print the error saying that the line does not contain a number
            }
        }
        br.close();
        System.out.println("Lowest number is " + lowestNumber);
    } catch (IOException ie) {
        // print the exception
    }
}

Need Your Help

No Matching Function Error for inserting into a list in c++

c++ list insert

I am getting an error when I try to insert an item into a list (in C++). The error is that there is no matching function for call to the insert(). I also tried push_front() but got the same error.

How to access the orm with celery tasks?

flask celery flask-sqlalchemy celery-task celerybeat

I'm trying to flip a boolean flag for particular types of objects in my database using sqlalchemy+celery beats. But how do I access my orm from the tasks.py file?