1

I'am trying to read a file which is .csv file into an array with the first index of each line in the file.

What I want to achieve is only the first word of each line, not like the image below:

Bonaqua
California
Gallardo
City
Skyline

dropbox image

Below is my read file class:

import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class readfile {

    private Scanner s;

    public void openFile() {
        try {
            s = new Scanner(new File(readpath.a));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "File not found!");
        }
    }

    public void readFile() {

        String read = "";

        while (s.hasNextLine()) {
            read += s.nextLine() + "\n";
        }

        String menu[] = read.split("\n");
        Object[] selectionValues = menu;
        String initialSelection = "";

        Object selection = JOptionPane.showInputDialog(null,
                "Please select the Topic.", "Reseach Forum Menu",
                JOptionPane.QUESTION_MESSAGE, null, selectionValues,
                initialSelection);

        JOptionPane.showMessageDialog(null, "You have choosen "
                        + selection + ".", "Reseach Forum Menu",
                JOptionPane.INFORMATION_MESSAGE);

        if (selection == null) {
            JOptionPane.showMessageDialog(null, "Exiting program...",
                    "Research Forum Menu", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
    }

    public void closeFile() {
        s.close();
    }
}

2 Answers 2

4

Change s.nextLine() to s.nextLine().split(",")[0]

Sign up to request clarification or add additional context in comments.

Comments

0

Can you tell my why you first concat the string with "\n"

while (s.hasNextLine()) {
            read += s.nextLine() + "\n";
}

and afterwards you split it?

String menu[] = read.split("\n");

That does not make sense to build a string and then split it the way you built it.

ArrayList<String> firstWords = new ArrayList<String>(); // ArrayList instead of a normal String list because you don't know how long the list will be.

while (s.hasNextLine()) {
    firstWords.add(s.nextLine().split(",")[0]);
}

Now you have all your first words in a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.