根据用户从扫描文件中输入的内容如何显示信息。

huangapple go评论73阅读模式
英文:

How to display message based on user input from scanned file

问题

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

我正试图弄清楚**如果价格与前一天相比增加了10%或更多,如何打印一条消息。**基本上,我如何从文本文件中获取信息,并找出两天内相同时间价格是否变化了10%,例如第一天和第二天都是中午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("文件未找到");
            e.printStackTrace();
        }
    }
}

非常感谢!

英文:

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!

答案1

得分: 1

使用方法

  • 使用Files.lines(...)逐行读取文件
  • 使用Stream<String>迭代行
  • 使用String.split(...)将每行拆分为价格和时间部分
  • 使用LocalDateTime.parse(...)将时间部分转换为LocalDateTime
  • 使用大小为2x24的矩阵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()) {  // 清除价格缓冲区以支持每行步骤 > 1 天
                    if (prevLineDayIdx.get() != -1) {
                        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("价格 " + price + " 在 " + 
                            format.format(timestamp) + 
                            " 与昨天同一时间的价格 " + 
                            previousPrice + 
                            " 相比相差10%或更多。"); 
                }
                prices[dayIdx%2][timeIdx] = price;
            });
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
}
英文:

Use

  • Files.lines(...) for reading the file line by line
  • Stream&lt;String&gt; 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(&quot;dd-MM-yyyy HH:mm&quot;);

    public static void main(String[] args) {
        Double[][] prices = new Double[2][24];
        AtomicInteger prevLineDayIdx = new AtomicInteger(-1);
        try (Stream&lt;String&gt; stream = Files.lines(Paths.get(&quot;price.txt&quot;))) {
                stream.forEach(line -&gt; {
                String[] ary = line.split(&quot; &quot;, 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 &gt; 1 days
                        for(int idx = prevLineDayIdx.get(); idx &lt; dayIdx - 1; idx ++) {
                            prices[idx%2] = new Double[24];
                        }
                    }
                    prevLineDayIdx.set(dayIdx);
                }
                Double previousPrice = prices[(dayIdx - 1)%2][timeIdx];
                if (previousPrice != null &amp;&amp;
                        Math.abs(previousPrice - price)/previousPrice &gt;= 0.1d) {
                    System.out.println(&quot;The price &quot; + price + &quot; on &quot; + 
                            format.format(timestamp) + 
                            &quot; differs 10% or more from the price &quot; + 
                            previousPrice + 
                            &quot; at the same time yesterday.&quot;); 
                }
                prices[dayIdx%2][timeIdx] = price;
            });
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }

}

huangapple
  • 本文由 发表于 2020年9月30日 02:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64125635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定