1

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?

1
  • java.util.StringTokenizer has been replaced with String.split(String). It's easier to use and makes your code a whole lot cleaner. Commented Apr 18, 2011 at 1:51

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

int y = m*x + b; sounds like some serious math to me just like the OP wanted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.