Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: How to parse Integer numbers (delimited by a variable number of spaces) in a line of a text file

I want to parse numbers in a line of a text file line by line. For example, imagine _ as a space

my text file content looks like:

___34_______45
_12___1000
____4______167
...

I think you got the idea. Each line may have variable number of spaces separating the numbers, meaning there is no pattern at all. The simplest solution could be read char by char and check if it is a number and go like that until the end of the number string and parse it. But there must be some other way. How can I read this in Java automatically so that I can get in a certain datastructure say array

[34,45]
[12,1000]
[4,167]
like image 423
Bob Avatar asked Sep 17 '12 02:09

Bob


1 Answers

Use java.util.Scanner. It has the nextInt() method, which does exactly what you want. I think you'll have to put them into an array "by hand".

import java.util.Scanner;
public class A {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int v1 = in.nextInt(); //34
    int v2 = in.nextInt(); //45
    ...
  }
}
like image 64
Jonathan Paulson Avatar answered Sep 28 '22 14:09

Jonathan Paulson