-1

I need to split a section of a file into doubles because its values will later be a a part of a graph amongst other things.

Here's a section of the file:

3000,1273010256, 2010/5/4,344,78.32,3.95
4000,1273010257, 2010/5/4,326,78.32,3.97
DLxe
  • 1
  • 3
  • Apart from 78.32 and 3.54 there aren’t any fractions in your data. Does using `double` make any sense? I’d prefer `int`, and probably `long` for the timestamp. Why aren’t you using the built-in `Instant` class for the times? With a conversion (to `OffsetDateTime`, for example) you can also get year, month, day, hour, etc., from it. – Ole V.V. Jan 09 '19 at 12:12
  • Apparently related: [Parsing different types of data format from a CSV file](https://stackoverflow.com/questions/53470278/parsing-different-types-of-data-format-from-a-csv-file) – Ole V.V. Jan 09 '19 at 12:15

2 Answers2

1

It's strange that you want all these values parsed to doubles, but anyway.
Since the value you want to split is datetime with format yyyy/M/d HH:mm:ss
you can do it by converting it to a LocalDateTime object and then extract each value:

String datetime = "2010/5/4 21:57:34";
LocalDateTime date = LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy/M/d HH:mm:ss"));

double YYYY = date.getYear();
double M = date.getMonthValue();
double d = date.getDayOfMonth();
double HH = date.getHour();
double mm = date.getMinute();
double ss = date.getSecond(); 

Alternative solution is to split once to get the date part and the hour part
and then split each part separately:

String datetime = "2010/5/4 21:57:34";

String[] tokens = datetime.split(" ");
String[] datepart = tokens[0].split("/");
String[] hourpart = tokens[1].split(":");

double YYYY = Double.parseDouble(datepart[0]);
double M = Double.parseDouble(datepart[1]);
double d = Double.parseDouble(datepart[2]);
double HH = Double.parseDouble(hourpart[0]);
double mm = Double.parseDouble(hourpart[1]);
double ss = Double.parseDouble(hourpart[2]);
forpas
  • 160,666
  • 10
  • 38
  • 76
0

In the initial question I don't see anything mentioning dates so I just see each line as a , separated list of values.

String in="3000,1273010256, 2010/5/4,344,78.32,3.95";
String[] fields=in.split(",");
double d1=Double.parseDouble(fields[4]);
double d2=Double.parseDouble(fields[5]);
System.out.println("d1="+d1);
System.out.println("d2="+d2);

Output is:

d1=78.32
d2=3.95
Conffusion
  • 4,335
  • 2
  • 16
  • 28