Home > Software engineering >  How to use data from a text file and use it
How to use data from a text file and use it

Time:11-16

I need to ask for a temperature (positive floating number from the user), read the temperatures (Celsius) from a text file (Temps.txt), Calculate the average, convert them to Fahrenheit, write the results in the console and generate a text file with the results. Also, check which temperatures from Temps.txt are greater or lesser than the temperature submitted.

NOTE:

I tried using a while loop to calculate the average but that didn't work since the result was 0.

Things left to do: Calculate the average, Convert the temperatures to Fahrenheit, Write the results to the console and output text.

I would appreciate some help. I've been advancing a little by little but I'm stuck over here.

    public static void main(String[] args) throws IOException {
        float   tempCelsius,
            celsius,
            farenheit = 0,
            amount,
            total = 0,
            avg;
        
        String  fileName = "Temps.txt", 
            line;   
                    
        File    file = new File(fileName);
    
        Scanner inFile,                     
            keyboard = new Scanner(System.in);

        int count = 1;                  
        
        
        do {
            System.out.print("Please enter a temperature in Celsius (Positive Number):  ");
        tempCelsius = keyboard.nextFloat();
        if (tempCelsius < 0) {
        System.out.printf("ERROR! %.2f is not positive\n", tempCelsius);
    
        }
            

        } while (tempCelsius < 0);
        if(!file.exists()) {
        System.out.printf("File \"%s\" does not exist.\n", fileName);
        }
        else {
            
            inFile = new Scanner(file);
            System.out.println("The Temperatures in Celsius Are: ");
            System.out.println("________________________________");
            while (inFile.hasNext()) {
                line = inFile.nextLine();
                System.out.println(count     ". "   line);
                celsius=Float.parseFloat(line);  
                farenheit = ((celsius*9)/5) 32;
                System.out.println("The temperatures in Farenheit are: "   farenheit);
            
            

            
            }
            while(inFile.hasNextFloat() ) 
            {
                
                amount = inFile.nextFloat();
                total =amount;
                
                if(amount!=0)
                {
                count  ;    
                }   

        }
            
        avg=total/count;
            
        System.out.println("The average of the temperatures in Celsius are: "   avg);
            
            inFile.close();
        }
                    
        System.out.println("\nExiting...");
    }
}

CodePudding user response:

The following class does read a positive decimal value from console, reads other decimals numbers from file "Temps.txt", computes the overall average in °C and °F for the items of file Temps.txt first, then from items of file and given input second.

It does not store the user's input in any file (like: append it to Temps.txt).

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {

        var filename = "Temps.txt";
        var input = 0f;

        try (var scanner = new Scanner(System.in)) {
            do {
                System.out.print("Please enter a temperature in Celsius (Positive Number):  ");
                input = scanner.nextFloat();

                if (input <= 0) {
                    System.out.printf("ERROR! %.2f is not positive\n", input);

                }

            } while (input <= 0);
        }

        var file = new File(filename);

        if (file.exists() && file.canRead()) {
            try (var scanner = new Scanner(file)) {

                var total = 0f;
                var items = 0;

                while (scanner.hasNextLine()) {

                    var item = Float.parseFloat(scanner.nextLine());

                    System.out.println(String.format("item %.2f is %s than input %.2f.", item,
                            (item > input ? "higher" : "lower or equal"), input));
                    total  = item;
                    items  ;

                }

                System.out.println(String.format("average temperature in °C: %.2f", (total / items)));
                System.out
                        .println(String.format("average temperature in °F: %.2f", celsiusToFahrenheit(total / items)));
                System.out.println(String.format("average temperature in °C (incl. input): %.2f",
                        ((total   input) / (items   1))));
                System.out
                        .println(String.format("average temperature in °F (incl. input): %.2f",
                                celsiusToFahrenheit((total   input) / (items   1))));
            }

        } else {
            System.err.println("Cannot find or read file "   filename);
        }
    }

    private static float celsiusToFahrenheit(final float celsius) {
        return ((celsius * 9) / 5)   32;
    }

}

  • Related