Chid Chid - 1 year ago 44
Java Question

Reading DATE type from text file

I have a text file which looks like this

2017-06-14 7932
2017-06-15 10092
2017-06-16 7626
2017-06-17 7613
2017-06-18 11072
2017-06-19 8286
2017-06-20 9293


I am trying to store the values in an
ArrayList
.

My Code:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.*;
import java.util.Scanner;

public class Sample2 {

public static void main(String[] args) throws FileNotFoundException {

List<Date> l1 = new ArrayList<Date>();
List<Integer> l2 = new ArrayList<Integer>();

Scanner s = new Scanner(new FileReader("t1.txt"));

while (s.hasNext()) {
l1.add(s.nextInt()); !!!!-----Error Line-----!!!!!!!!
l2.add(s.nextInt());
}


s.close();

System.out.println(l1);
System.out.println(l2);;
}
}


I get the Following Error:


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method add(int, Date) in the type List is not
applicable for the arguments (int)
at Sample2.main(Sample2.java:17)


How do I fix it?

Answer Source

You need to check for an int by using the nextInt() method.

"else" s.next() will return a String.

This will fix your error:

while (s.hasNext()) {
   if (s.hasNextInt()) {
       int myInt = s.nextInt();
       System.out.println(myInt);
   } else {
       String dateAsString = s.next();
       System.out.println(dateAsString);
   }
}

When I run this code, I get:

2017-06-14
7932
2017-06-15
10092
2017-06-16
7626
2017-06-17
7613
2017-06-18
11072
2017-06-19
8286
2017-06-20
9293

You will have to convert your date string to a localDate() or Date()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download