【问题标题】:How to display message based on user input from scanned file如何根据扫描文件中的用户输入显示消息
【发布时间】:2020-09-29 18:35:13
【问题描述】:

我有一个类,它根据用户输入的价格创建一个文本文件并放置一个时间戳,然后我可以在另一个类中读取该文件。

我正在尝试如果价格与前一天相差 10% 或更多,如何打印消息。基本上我如何从文本文件中获取信息并计算价格是否在同一时间的 2 天之间变化了 10%,即第一天下午 12 点和第二天下午 12 点。

例如,如果周二上午 11 点的值为 50,周三的值为 60,则应打印“11 点​​的价格超过 10%”

这是创建文件的代码:

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();
        }
    }  
}

price.txt 如下所示:

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

这是我阅读 price.txt 文件的方式:

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();
        }
    }
}

非常感谢!

【问题讨论】:

  • 请描述您的问题。
  • 对不起,我会尽量让它更清楚
  • 时间戳 12:54:41 是截断到 12 还是舍入到最近的 13 小时?如果四舍五入为 13,将使用哪个值:55 12:54:41 还是 60 13:08:16?
  • 嗨 @haba713 它被截断为 12

标签: java class java.util.scanner java-io println


【解决方案1】:

使用

  • Files.lines(...) 用于逐行读取文件
  • Stream<String> 用于遍历行
  • String.split(...) 将每一行拆分为价格和时间部分
  • LocalDateTime.parse(...) 将时间部分转换为LocalDateTime
  • 2 x 24 矩阵 Double[][] 用于缓冲两天的每小时价格
  • 模运算符 % 用于在偶数天和奇数天之间切换。

查看此实现:

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();
        }        
    }

}

【讨论】:

  • 非常感谢,效果很好!我有一个小错误,我收到了Exception in thread "main" java.lang.NumberFormatException: empty String 任何想法如何解决这个问题?
  • 你能shareyour price.txt 吗?
  • 当然,pastebin.com/CfLc87J4,我删除了秒数,因为我认为我的项目不需要它。
  • 我相应地更改了格式字符串H:mm:ssHH:mm。但是,我无法复制NullFormatException。查看输出here
  • 非常感谢!我刚刚发现了问题,我在 price.txt 文件的 48 行之后有一些额外的空行。再次感谢您的帮助,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多