Reputation: 3
I'm attempting to read a text file with Scanner dataFile = new Scanner("FileName.txt");
the text file has lines which are supposed to be read for info on them. I'm using:
while(dataFile.hasNext()){
String line = dataFile.nextLine();
...
}
to loop through the lines. I need to extract a String at the start of the line, an Integer after the String, and a Double after the Integer. They have spaces in-between each part I need to extract so I am willing to \ make a substring search through the line to individually search for the parts in the line.
I am wondering, Is there an easier and quicker method to doing this?
Example contents of text file:
Name 10 39.5
Hello 75 87.3
Coding 23 46.1
World 9 78.3
Upvotes: 0
Views: 91
Reputation: 13
substring search?
you may use
String[] str=line.split(" ");
and then str[0] is the string you find
str[1] is the string of Integer ,you cast it
and the str[2] is the string of Double , cast
Upvotes: 0
Reputation: 375
If they're all the same format, you can split on whitespace.
String str = "Name 10 39.5";
String[] arr = str.split(" ");
String s = arr[0];
int i = Integer.valueOf(arr[1]);
double d = Double.valueOf(arr[2]);
Upvotes: 1