I’m trying to make a simple scanner reader to read from a txt stored in C:UsersjamesDesktopprojectfiles and it’s called data “data.txt”, the thing is that the information stored is like this:
ASSETS 21 CHOROY 12 SHELL 9
So as you can see the spaces between the string and the integer that I want o extract are random. I was trying to make this:
public data(String s) //s is the name of the txt "data.txt" { if (!s.equalsIgnoreCase("Null")) { try { File text = new File(s); Scanner fileReader = new Scanner(text); while (fileReader.hasNextLine()) { String data = fileReader.nextLine(); String[] dataArray = data.split(" "); String word = dataArray[0]; String number = dataArray[1]; int score = Integer.parseInt(number); addWord(word, score); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } System.out.println("Reading complete"); }
But the split is only with one empty space between the string and the integer so I would like to know how can I extract that two things that are separated with any number of spaces in the same line. Example:
Line readed: HOUSE 1 -> String word = "HOUSE"; int score = "1"; Line readed: O 5 -> String word = "O"; int score = "5";
Advertisement
Answer
Instead of data.split(" ")
you can use
data.split("\s+")
Also your function won’t compile because it does not have any return.