目前我正在編寫一個java程序,以查明在哪一天形成了錘子或其他燭臺圖案。用戶在執行程序時必須輸入2個日期作爲參數,例如, java ReadingTest 2016-09-03 2016-10-31,程序會自2016-09-03至2016-10-31查找錘子模式。 代碼如下:解析if語句中的日期並僅顯示規定時間範圍內的結果
import java.io.*;
import java.util.*;
import java.text.*;
public class ReadingTest
{
public static void main(String[] args) throws IOException,ParseException
{
//Import file to java
File file = new file("table.csv");
//Read the file
Scanner infile = new Scanner(file);
//Skip the first line in table.csv
infile.nextLine();
//Define format of date
SImpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//Name the variables user enters
Date start = sdf.parse(args[0]);
Date end = sdf.parse(args[1]);
//Create ArrayList for each column of data
ArrayList<String> date = new ArrayList<String>();
ArrayList<Double> open = new ArrayList<Double>();
ArrayList<Double> high = new ArrayList<Double>();
ArrayList<Double> low = new ArrayList<Double>();
ArrayList<Double> close = new ArrayList<Double>();
while (infile.hasNext())
{
//Tokenize columns by comma
String[] data = infile.nextLine().split(",");
//Organize each column of data to one index of data array
date.add(data[0]);
open.add(Double.parseDouble(data[1]));
high.add(Double.parseDouble(data[2]));
low.add(Double.parseDouble(data[3]));
close.add(Double.parseDouble(data[4]));
}
//Show options and ask user to choose
System.out.println("1. Hammer");
System.out.println("2. Three white soldiers");
System.out.println("3. Bullish kicker");
//Record user input and execute corresponding code
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1)
for (int i = 0; i < date.size(); i++)
if (close.get(i) > open.get(i) &&
close.get(i) > ((high.get(i)) + (low.get(i)))/2 &&
((close.get(i) - low.get(i))/2 > (high.get(i) - close.get(i)))
System.out.println("Pattern found: " + date.get(i));
}
}
該代碼完美工作到這裏。但是,最後一行代碼中的輸出是dd/MM/yyyy格式,我嘗試使用sdf.parse(date.get(i))而不是date.get(i)以yyyy-MM顯示結果-dd格式。運行與sdf.parse(date.get(i))的代碼返回以下錯誤:
Exception in thread "main" java.text.ParseException: Unparseable date:
"25/10/2016" at
java.text.DateFormat.parse(Unknown source) at ReadingTest.main(ReadingTest.java:59)
我也試圖只顯示日期在
表明使用(date.get(i).after(start) && date.get(i).before(end))
和結果的錘圖案
error: cannot find symbol
symbol: method before(Date)
location: class String
而且CSV文件看起來像這樣:
Date Open High Low Close
31/10/2016 58.25 58.65 58.2 58.35
28/10/2016 58.95 59 58.3 58.35
.
.
.
1/8/2016 50.8 51.1 50.75 50.8
如何修改代碼以使其工作?
由於某些基本的拼寫錯誤(即主函數開頭的缺失括號),您的代碼不會編譯。下次嘗試提供適當的代碼示例。 – BaptisteL
順便說一句,您正在使用舊的日期 - 時間類,現在是遺留下來,由java.time類代替。 –