编写一个名为UploadData的方法来执行此任务。选择适当的参数并返回类型。
输入文件格式:
月日年产量
样本输入文件:
2018年1月10日236.9 2018年1月11日267.6 2018年1月12日278.1
然后,我必须编写另一个方法来显示已读取的内容。 这是我到目前为止所拥有的。
public static ArrayList<String> uploadData() throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the file");
String fileName = keyboard.nextLine();
ArrayList<String> List = new ArrayList<String>();
File myFile = new File(fileName);
Scanner scan = new Scanner(myFile);
while (scan.hasNextLine()) {
String n = scan.nextLine();
scan.next();
System.out.println(scan.next());
}
ArrayList<String> end = new ArrayList();
return end;
}
答案 0 :(得分:0)
我认为您必须使用Regular Expression将值分成一行。尝试以下代码:
public static ArrayList <String> uploadData() throws IOException {
//this pattern can separate the string in multiple dates base on format of your example input file
Pattern pattern = Pattern.compile("(\\w+ \\d{1,2} \\d{4} \\d{3}\\.\\d{1})");
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter the name of the file");
String fileName= keyboard.nextLine();
// dateList is a better name than List
ArrayList <String> dateList = new ArrayList <String>();
File myFile= new File(fileName);
Scanner scan = new Scanner (myFile);
while(scan.hasNextLine()) {
String n = scan.nextLine();
Matcher matcher = pattern.matcher(n);
// each date thats matches the pattern will be added to the list
while(matcher.find()) {
dateList.add(matcher.group());
}
}
for (String dateString: dateList) {
System.out.println(dateString);
}
return dateList;
}
答案 1 :(得分:0)
无需我为您编写半伪代码,就可以帮助您走上正确的道路。仅当数据始终像样本输入一样完美地构造时,此方法才有效。这可能也不是最好的方法:),但是您可以找出可以进行的任何改进。
uploadData
ArrayList<Data> dataToPrint = ....
while(input.nextLine)
String line = input.getline
String[] dataArray = line.split(" ") //split on space
count = 1
Data d;
for(int i=0; i<dataArray.length; i++)
if count == 1
d = new Data
d.setMonth(dataArray[i])
if count == 2
d.setDay(...)
if count == 3
d.setYear(...)
if count == 4
d.setAmount(...)
dataToPrint.add(d)
count = 1
数据类
Data
String month
int day
int year
float amount