YJay
YJay

Reputation: 91

How to display message based on user input from scanned file

I have a class that creates a text file based on user input for price and puts a time stamp and I can then read the file in another class.

I'm trying to figure how to print a message if the price is different then the day before by 10% or more. Basically how can I take the information from the text file and figure out if the price changed by 10% between the 2 days for the same time, so 12 pm on the first day and 12 pm on the next day.

For example if at 11 am on Tuesday the value is 50, and the value is 60 on Wednesday, it should print "price at 11 is more than 10%"

This is the code for creating the file:

class Main{  
    public static void main(String args[]){  
        Scanner scan = new Scanner(System.in);
        System.out.println("Price: ");
        float price = scan.nextInt();
        System.out.println( "Price:" + " " + price);
        LocalDateTime dateTime = LocalDateTime.now(); 
        DateTimeFormatter formatDT = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
        String formattedDT = dateTime.format(formatDT);
        scan.close();

        try(FileWriter fw = new FileWriter("price.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw))
        {
            out.println(price + " " + formattedDT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  
}

The price.txt looks like this:

50 29-09-2020 11:49:54
55 29-09-2020 12:54:41
60 29-09-2020 13:08:16
58 29-09-2020 14:08:21
...
60 30-09-2020 11:29:34
56 30-09-2020 12:34:21
60.3 30-09-2020 13:48:36
58.1 30-09-2020 14:18:11

and here is how I read the price.txt file:

public class ReadFile {
    public static void main(String[] args) {
        try {
            File readFile = new File("price.txt");
            Scanner fileReader = new Scanner(readFile);
            while (fileReader.hasNextLine()) {
                String fileContent = fileReader.nextLine();
                System.out.println(fileContent);

            }
            fileReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("file was not found");
            e.printStackTrace();
        }
    }
}

Thanks so much!

Upvotes: 0

Views: 625

Answers (1)

haba713
haba713

Reputation: 2687

Use

  • Files.lines(...) for reading the file line by line
  • Stream<String> for iterating through the lines
  • String.split(...) to split each line to price and time parts
  • LocalDateTime.parse(...) to convert time part to LocalDateTime.
  • 2 x 24 matrix Double[][] for buffering hourly prices for two days
  • Modulo operator % for switching between even and odd days.

See this implementation:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class ReadFile {
    
    private static final DateTimeFormatter format =
            DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

    public static void main(String[] args) {
        Double[][] prices = new Double[2][24];
        AtomicInteger prevLineDayIdx = new AtomicInteger(-1);
        try (Stream<String> stream = Files.lines(Paths.get("price.txt"))) {
                stream.forEach(line -> {
                String[] ary = line.split(" ", 2);
                Double price = Double.parseDouble(ary[0]);
                LocalDateTime timestamp = LocalDateTime.parse(ary[1], format);
                int dayIdx = (int) timestamp.toLocalDate().toEpochDay();
                int timeIdx = timestamp.getHour();
                if (dayIdx != prevLineDayIdx.get()) {  // Clear price buffer for 
                    if (prevLineDayIdx.get() != -1) {  // supporting line step > 1 days
                        for(int idx = prevLineDayIdx.get(); idx < dayIdx - 1; idx ++) {
                            prices[idx%2] = new Double[24];
                        }
                    }
                    prevLineDayIdx.set(dayIdx);
                }
                Double previousPrice = prices[(dayIdx - 1)%2][timeIdx];
                if (previousPrice != null &&
                        Math.abs(previousPrice - price)/previousPrice >= 0.1d) {
                    System.out.println("The price " + price + " on " + 
                            format.format(timestamp) + 
                            " differs 10% or more from the price " + 
                            previousPrice + 
                            " at the same time yesterday."); 
                }
                prices[dayIdx%2][timeIdx] = price;
            });
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }

}

Upvotes: 1

Related Questions