I have a text file that contains the following:
Hello
1
2
3
4
5.6
LOL
23.5
34.6
23
456
Rofl.
I wrote down the code in java that would read the contents of this text file and distinguish between the 3 data types.I used try catch statements and my code works(kinda). The only problem is that it converts any whole numbers to doubles as well. For example the following is what my code is outputting:
List of integers in the textfile: [1, 2, 3, 4, 23, 456]
List of doubles in the textfile: [1.0, 2.0, 3.0, 4.0, 5.6, 23.5, 34.6, 23.0, 456.0]
List of Strings in the textfile: [Hello, 5.6, LOL, 23.5, 34.6, Rofl]
I want to prevent that from happening. Any suggestions would be appreciated.
ArrayList<Integer> data_int=new ArrayList<Integer>();
ArrayList<String> data_String=new ArrayList<String>();
ArrayList<Double> data_double=new ArrayList<Double>();
while(file.hasNext())
{
String s=file.next();
System.out.println(s);
try
{
Integer.parseInt(s);
data_int.add(Integer.parseInt(s));
}
catch(NumberFormatException e)
{
data_String.add(s);
}
try
{
Double.parseDouble(s);
data_double.add(Double.parseDouble(s));
}
catch(NumberFormatException e)
{
}
}
System.out.println("List of integers in the textfile: "+data_int);
System.out.println("List of doubles in the textfile: "+data_double);
System.out.println("List of Strings in the textfile: "+data_String);