0

I have a file named "data.txt" and it look like this:

B,C,1,360,370,380,390,400,410,420
B,C,2,365,375,385,395,405,415,425
B,G,3,360,370,380,390,400,410,420
C,D,1,370,380,390,400,410,420,430
C,D,4,385,395,405,415,425,435,445
C,G,5,360,370,380,390,400,410,420
D,G,3,365,375,385,395,405,415,425
G,B,3,385,395,405,415,425,435,445
G,D,3,380,390,400,410,420,430,440

I have to do a function like this Function(String s1, String s2, int x) it will output the value after the second comma from the left if it satisfies the condition: -s1 must equal the first value -s2 is equal to the value after the first comma -Finally return the first value bigger than "x" from the 3rd comma. Example Function ("B", "C", 364) = 1 and Function ("B", "C", 366) = 2. I tried to read the file line by line then split using this

    BufferedReader reader;
        String fileName = "data.txt";
        try(Stream<String> stream = Files.lines(Paths.get(fileName),StandardCharsets.UTF_8)){
            stream.forEach(line ->{
                System.out.println(line);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

So i can print the file in Console. I add split (). To take each character and compare it, but the results printed in the Console are not as I thought.

BufferedReader reader;
            String fileName = "data.txt";
            try(Stream<String> stream = Files.lines(Paths.get(fileName),StandardCharsets.UTF_8)){
                stream.forEach(line ->{
                String[] newline=line.split(",");
                System.out.println(newline);

                });
            } catch (Exception e) {
                e.printStackTrace();
            }

Here is the console:

[Ljava.lang.String;@8646db9
[Ljava.lang.String;@37374a5e
[Ljava.lang.String;@4671e53b
[Ljava.lang.String;@2db7a79b
[Ljava.lang.String;@6950e31
[Ljava.lang.String;@b7dd107
[Ljava.lang.String;@42eca56e
[Ljava.lang.String;@52f759d7
[Ljava.lang.String;@7cbd213e

I'm stuck at here now.

  • 2
    Okay, so the requirements are clear. What is your question? What have you tried? Where specifically are you stuck? – Joachim Sauer Apr 29 '20 at 14:44
  • I will update the question now. Thx – Hoàng Phạm Apr 29 '20 at 14:47
  • You should look up `String#split` and `Integer.parseInt`; they'll help you here. – user Apr 29 '20 at 14:48
  • You are reading the file but you are not storing the result, what about creating a List that holds each array (`newLine`) or another list for each row and then use that list in the search method you are supposed to write. – Joakim Danielson Apr 29 '20 at 15:08
  • @JoakimDanielson I will try it now. Thank – Hoàng Phạm Apr 29 '20 at 15:09
  • System.out.println(newline) gives the reference of newline array and it is correct. If you want to print the content of the newline array you have to do something like this: for (String s:newline) System.out.println(s); –  Apr 29 '20 at 15:29
  • Does this answer your question? [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Bernhard Stadler Apr 29 '20 at 16:46

1 Answers1

0

I believe the following does what you desire. It reads the file data.txt and locates the first line in the file that matches your criteria. If such a line is found, then the third field in that line is extracted, converted to an int and that int is returned by the method (named function). If no matching record is found, then method function returns -1 (minus one).

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Predicate;

public class FltrStrm {
    private static int function(String s1, String s2, int x) throws IOException {
        Predicate<String> predicate = line -> {
            boolean accepted = false;
            if (line != null  &&  !line.isEmpty()) {
                String[] fields = line.split(",");
                if (fields.length == 10) {
                    try {
                        int number = Integer.parseInt(fields[3]);
                        accepted = s1.equals(fields[0])  &&
                                   s2.equals(fields[1])  &&
                                   number > x;
                    }
                    catch (NumberFormatException xNumFmt) {
                        // Ignore
                    }
                }
            }
            return accepted;
        };
        Path path = Paths.get("data.txt");  // replace 'data.txt' with your actual path
        Optional<String> record = Files.lines(path, StandardCharsets.UTF_8)
                                       .filter(predicate)
                                       .findFirst();
        int index = -1;
        if (record.isPresent()) {
            try {
                index = Integer.parseInt(record.get().split(",")[2]);
            }
            catch (NumberFormatException xNumFmt) {
                // Ignore.
            }
        }
        return index;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String s1 = "B";
        String s2 = "C";
        int x = 364;
        try {
            int index = function(s1, s2, x);
            if (index >= 0) {
                System.out.println("Found: " + index);
            }
            else {
                System.out.println("Nothing found.");
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

Running the above code using the sample data from your question outputs the following.

Found: 2
Abra
  • 19,142
  • 7
  • 29
  • 41