user3773893
user3773893

Reputation: 7

reading data from text file and validate it

I have a text file and i need to read data from it to a 2D array. the file contains string as well as numbers.

String[][] arr = new String[3][5];    
BufferedReader br = new BufferedReader(new FileReader("C:/Users/kp/Desktop/sample.txt"));    
String line = " ";    
String [] temp;
    int i = 0;
    while ((line = br.readLine())!= null){ 
        temp = line.split(" "); 
        for (int j = 0; j<arr[i].length; j++) {    
            arr[i][j] = (temp[j]);
        }
        i++;
    }

sample text file is : name age salary id gender
jhon 45 4900 22 M
janey 33 4567 33 F
philip 55 5456 44 M

now, when the name is a single word without any space in between, the code works. but it doesn't work when the name is like "jhon desuja". How to overcome this?

I need to store it in a 2d array. how to validate the input? like name should not contain numbers or age should not be negative or contain letters. any help will be highly appreciated.

Upvotes: 0

Views: 1342

Answers (1)

Aimee Borda
Aimee Borda

Reputation: 842

Regular Expression might be a better options:

Pattern p =     Pattern.compile("(.+) (\\d+) (\\d+) (\\d+) ([MF])");
String[] test = new String[]{"jhon 45 4900 22 M","janey 33 4567 33 F","philip 55 5456 44 M","john mayer 56 4567 45 M"};
for(String line : test){
  Matcher m = p.matcher(line);
  if(m.find())
    System.out.println(m.group(1) +", " +m.group(2) +", "+m.group(3) +", " + m.group(4) +", " + m.group(5));
}

which would return

jhon, 45, 4900, 22, M
janey, 33, 4567, 33, F
philip, 55, 5456, 44, M
john mayer, 56, 4567, 45, M

Upvotes: 2

Related Questions