0

Suppose i have a text file that has a number code and a string label on each line:

0102 Apple Banana Code
0203 Pear Watch Time
0405 Java Computer Pen
0607 Car Bike Drive

How could i print the sum of the non zero numbers in the front and the first two words of each line? Assuming that the numbers are always 4 digits and words are separated by a single space from the number and in between the words. For example I would get:

3 Apple Banana 
5 Pear Watch 
9 Java Computer 
13 Car Bike 

I have tried to initialize this but i have no idea where to go from here

FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
String[][] words = new String[100][];
String line;
int size = 0;
while((line = inFile.readLine()) != null) {
    words[size++] = line.split(" ");
}
inFile.close();
user
  • 11

1 Answers1

0

You are close. Refer to below code. Explanations appear after the code.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Tester {
    private static void handleLine(String line) {
        String[] parts = line.split(" ");
        int num = handleNumber(parts[0]);
        System.out.printf("%d %s %s%n", num, parts[1], parts[2]);
    }

    private static int handleNumber(String number) {
        char[] digits = number.toCharArray();
        int total = 0;
        for (char digit : digits) {
            total += digit - '0';
        }
        return total;
    }

    public static void main(String[] args) {
        Path path = Path.of("tragedy.txt");
        try (BufferedReader inFile = Files.newBufferedReader(path)) {
            String line = inFile.readLine();
            while (line != null) {
                handleLine(line);
                line = inFile.readLine();
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}
  • I use class Files to create a BufferedReader but it is not required. Your code for obtaining a BufferedReader is correct.
  • I also use try-with-resources to ensure that the file is closed.
  • You asked how to print the file lines after manipulating them slightly so that is what the above code does.
  • char is actually a number so to get the actual number value from the char, I subtract the value of the 0 character.
Abra
  • 19,142
  • 7
  • 29
  • 41