【发布时间】: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