the data file contains:

1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
1910,Newtown,Souths,Newtown,Wests,Y,4,4,14000
1911,Easts,Glebe,Glebe,Balmain,Y,11,8,20000

Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score, losing score, crowd

What I need is to display a list of Grand Final held as 'Y'. In other words, how do I display a list of 'Y' which is after the 5th comma?

import java.io.*;
import java.util.ArrayList;

public class GrandFinal {

    private static BufferedReader br = null;
    private static ArrayList<String> al = new ArrayList<String>();
    private static String line = "";

    public static void storeArray() {       
        try {            
            br = new BufferedReader(new FileReader("NRLdata.txt"));
            while ((line = br.readLine()) != null)
                al.add(line);
        }
        catch (Exception e) {
            System.out.println("Unable to find file.");
        }

        for (int i = 0; i < al.size(); i++) {
            // this line.
            }
        }
    }
}

Dani AI

Generated

The file is a simple CSV where the sixth comma‑separated field indicates whether a Grand Final was held. was right to suggest checking that field — the problems in the code shown here are off‑by‑one indexing, misuse of Scanner with a comma delimiter (which tokenises the whole file into single fields so you end up printing the Y tokens only), and incorrect use of String APIs (e.g. using indexOf where an equality check is needed). ’s scanner loop also increments the index before storing, which leaves a null at index 0 and shifts everything.

A reliable pattern: read the file line by line (record level), extract the sixth field, trim it and compare exactly to "Y" (case‑insensitive if you want). Avoid contains("Y") because that matches names that include the letter Y. Also always defensively check field count before accessing index 5.

A concise, robust example using a regex to capture the 6th field and Java NIO (different approach than the examples above):

import java.nio.file.*;
import java.util.regex.*;
import java.io.IOException;
import java.util.stream.Stream;

public class GrandFinalList {
    private static final Pattern SIXTH_FIELD = Pattern.compile("^(?:[^,]*,){5}([^,]*)");

    public static void main(String[] args) throws IOException {
        Path p = Paths.get("NRLdata.txt");
        try (Stream<String> lines = Files.lines(p)) {
            lines.map(String::trim)
                 .filter(line -> !line.isEmpty())
                 .filter(line -> {
                     Matcher m = SIXTH_FIELD.matcher(line);
                     return m.find() && "Y".equalsIgnoreCase(m.group(1).trim());
                 })
                 .forEach(System.out::println);
        }
    }
}

Quick troubleshooting: print the raw line and the captured 6th field when results are unexpected; confirm the file path/encoding; handle blank lines and malformed rows by skipping or logging them. This approach preserves full lines for output and avoids tokenising the entire file into individual fields.

Recommended Answers

All 6 Replies

you can use String's split method with comma as separator, and then check if the 6th element is Y.
if so, print, if not, don't.

for (int i = 0; i < al.size(); i++) {
            String[] parts = al.get(i).split(",");
            System.out.println(parts[i]);
        }

How's that? It doesn't display properly.

why are you not using your 'line' variable?

anyway, "doesn't display properly" doesn't really tell us much.
what I suggested was: check the element of parts with index 5. if that equals "Y", then print al.get(i), not parts with index i.

I am apologise for the inconvenience. Umm what I have wrote is

for (int i = 0; i < al.size(); i++) {
            String[] parts = al.get(i).split(",");
            if(parts[i].indexOf(5).equals("Y"))
                System.out.println(al.get(i));
        }

But the 3rd line has an error. Not sure what's wrong with it.

I made a new code over again without using Linked List since I wasn't taught to use Linked List, instead of the regular array. Here's the code:

import java.io.*;
import java.util.Scanner;

public class GrandFinal {
    public static Scanner file;
    public static String[] array = new String[1000];

    public static void main(String[] args) throws FileNotFoundException {
        File myfile = new File("NRLdata.txt");
        file = new Scanner (myfile);
        Scanner s = file.useDelimiter(",");
        int i = 0;
        while (s.hasNext()) {
            i++;
            array[i] = s.next();
        }
        /*
        for(int j=0; j<array.length; j++) {
        if(array[j] == null)
            ;
        else
            System.out.print(array[j] + " ");
        }
        */

        for(int j=0; j<array.length; j++) {
            if(array[j] == null)
                ;
            else if(array[j].contains("Y"))
                System.out.println(array[j] + " ");
        }
    }
}

When I ran the program it just displayed "Y Y Y Y Y Y Y..." which is not what I expected. What I need is to display all seasons with "Y".

for (int i = 0; i < al.size(); i++) {
            String[] parts = al.get(i).split(",");
            if(parts[i].indexOf(5).equals("Y"))
                System.out.println(al.get(i));
        }

here you were on the right track, but what exactly do you need that 'indexOf' for? just look in the api for String, and you'll see that 's not what you want at all.

at that part, you have an array of Strings of (minimal) 6 elements.
what you need to do is check whether or not the 6th element (index = 5) equals "Y", so just replace the above code with:

for (int i = 0; i < al.size(); i++) {
            String[] parts = al.get(i).split(",");
            if(parts[5].equals("Y"))
                System.out.println(al.get(i));
        }

and try again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.