开发者

Clean way to import data from a text file?

开发者 https://www.devze.com 2022-12-17 00:42 出处:网络
I have a text file with the following in it: name1:0|0|0|0|0| name2:0|0|0|0|0| ... etc I\'m importing the names into an array of Strings.

I have a text file with the following in it:

name1:0|0|0|0|0|

name2:0|0|0|0|0|

... etc

I'm importing the names into an array of Strings.

That's fine, however I can't think of a clean way to associ开发者_如何学Goate the numbers with the array item. The numbers are separated by a "pipe" '|' character

Ideally I'd like to call a method which returns an array of Integers when given the name i.e. something like public int[] getScores(String name)


Scanner can also do it (since Java 1.5). The advantages over String#split is that you get some sort of automatic type conversion using regular expressions.

Example from javadoc

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close(); 

Also, if your aim is to recover the numbers by their name, use some kind of hash table to store it for faster retrieval.


Use string split

First use : to split a line, then use | to split out each number as a string. At last use Integer.Parse to get the numbers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号