0

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
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Drew
  • 3
  • 2

2 Answers2

1

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]);
Touniouk
  • 375
  • 1
  • 13
  • 1
    You might want to split on `\\s+`, if there is any chance that there could more than one whitespace character, or whitespace other than space. – Tim Biegeleisen Nov 20 '17 at 01:50
0
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
Joe F
  • 13
  • 2