开发者

convert line from text file into variables JAVA

I'm trying to extract the numbers individual lines from a text file and perform an operation on them and print them to a new text file.

my text file reads somethings like

10 2 5 2

10 2 5 3

etc...

Id like to do some serious math so Id 开发者_如何转开发like to be able to call upon each number from the line I'm working with and put it into a calculation.

It seems like an array would be the best thing to use for this, but to get the numbers into an array do I have to use a string tokenizer?


Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextLine()) {
    String[] numstrs = sc.nextLine().split("\\s+"); // split by white space
    int[] nums = new int[numstrs.length];
    for(int i = 0; i < nums.length; i++) nums[i] = Integer.parseInt(numstrs[i]);

    // now you can manipulate the numbers in nums[]

}

Obviously you don't have to use an int[] nums. You can instead do

int x = Integer.parseInt(numstrs[0]);
int m = Integer.parseInt(numstrs[1]);
int b = Integer.parseInt(numstrs[2]);
int y = m*x + b; // or something? :-)

Alternatively, if you know the structure ahead of time to be all ints, you could do something like this:

List<Integer> ints = new ArrayList<Integer>();
Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextInt()) {
    ints.add(sc.nextInt());
}

It creates Integer objects which is less desirable, but isn't significantly expensive these days. You can always convert it to an int[] after you slurp them in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜