lecardo
lecardo

Reputation: 1212

Read first character on each line in a file

I have a file in this format:

0 2 4
3 2 4
3 5 2
1 8 2

My aim is to read the first line on each file and store it in a array. So at the end I should have 0,3,3,1

I thought one approach would be, read the line until we encounter a space and save that in a array...but it would keep on reading 2 and 4 after

Is there a efficient way of doing this, my cod is shown below:

openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt"))) 
    {
        String line;
        while ((line = br.readLine()) != null) {
        int change2Int=Integer.parseInt(line.trim());
        figures [i] = change2Int;
        i++;
        }
    }
catch (Exception expe)
    {
    expe.printStackTrace();
    }

}

Upvotes: 1

Views: 9831

Answers (3)

singhakash
singhakash

Reputation: 7919

Try

int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');

or

int change2Int=Character.getNumericValue(line.charAt(0));

with your approch you are reading the whole line and parsing it to int which will give you NumberFormatException because of the space between the digits.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311228

Using a Scanner would make the code considerably cleaner:

private static openandprint() throws IOException {
    int i = 0;
    try (Scanner s = new Scanner("final.txt")))  {
        String line;
        while (s.hasNextLine()) {
            int change2Int = s.nextInt();
            s.nextLine(); // ignore the rest of the line
            figures [i] = change2Int;
            i++;
        }
    }
}

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
  String[] parts = line.split(" ");
  int next = Integer.parseInt(parts[0]);
  System.out.println("next: " + next);
}

Upvotes: 0

Related Questions