Jonathan Laliberte
Jonathan Laliberte

Reputation: 179

Getting the first word from each line?

Having a hard time getting the first word from each line. Any ideas why it's outputting blank files?

The program takes the following text as input:

abecedism   word created from the initials of words in a phrase
ablaut  variation in root vowel of words to change meaning
acronym word formed from initial letters of another word
acrophonic  using a symbol for the initial sound of a thing
acroteleutic    phrase or words at the end of a psalm
adversative word or phrase expressing opposition

And the aim is to get the results to look like this:

abecedism   
ablaut  
acronym 
acrophonic  
acroteleutic    
adversative 

Here is the code so far:

public static void main(String args[]) {
    String fileNameOutput = "OutputFile.txt";
    String fileName = "InputWords.txt";
    Charset cs = Charset.defaultCharset();
    try (BufferedReader bReader = Files.newBufferedReader(Paths.get(fileName), cs)) {
        PrintWriter outputStream = new PrintWriter(fileNameOutput);
        int lineNum = 0;
        String line = null;
        while ((line = bReader.readLine()) != null) {
            lineNum++;
            if (line.split(" ").length > 1) continue;
            outputStream.println(line);
        }
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 2

Views: 8639

Answers (7)

Pshemo
Pshemo

Reputation: 124225

if (line.split(" ").length > 1) continue;

checks if line contains more than one words/tokens and if it does it immediately starts new iteration which means you are skipping rest of code after continue which prevents you from executing

outputStream.println(line);

and since each line in your file has more that one word you are not adding anything to result file.


Your code could probably be simplified a little with Scanner class which allows us to iterate over words/tokens using next() method.

try (Scanner sc = new Scanner(new File(fileName));
     PrintWriter outputStream = new PrintWriter(fileNameOutput);) {
    while (sc.hasNextLine()) {
        outputStream.println(sc.next());// write first word from line
        sc.nextLine();// consume rest of text from that line
    }
} catch (IOException e) {
    e.printStackTrace();
}

Note: don't call close() inside try section. If some exception would occur outputStream.close(); for your PrintWriter outputStream wouldn't be called which could make a lot of problems. You should move declaration of closable resources as part of try-with-resources.

Upvotes: 3

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

if you have input as string you can simply use a regular expression to get it

String[] words = input.split("[ ].*$*[\n\r]{0,}");

and if you are reading from file then either you can read entire string from file using

String input = new String(Files.readAllBytes(Paths.get("..your path..")));

or you can iterate over each line if you have large data and you don't want to do it at a glance, then you can follow other approaches as well, and extract first word from each line.

Upvotes: 1

Roel Strolenberg
Roel Strolenberg

Reputation: 2950

The problem lies here:

if (line.split(" ").length > 1) continue;

Each line has more than 1 space, so the code:

outputStream.println(line.split(" ")[0]);

is never executed, since continue skips directly to the next while iteration So remove the if (line.split(" ").length > 1) continue; check

EDIT Added line.split(" ")[0] in print message to only get first word

Upvotes: 4

radoh
radoh

Reputation: 4809

That split is unnecessary, you can do basically

while ((line = bReader.readLine()) != null) {
    lineNum++;
    int spaceIndex = line.indexOf(" ");
    String firstWord = spaceIndex > -1 ? line.substring(0, spaceIndex) : line;
    outputStream.println(firstWord );
}

You can add another check if the line is empty...

Upvotes: 1

Charif DZ
Charif DZ

Reputation: 14721

you need to use find the value of index of the first blank space then use substring methode to cut the string line from 0 to index of f

Upvotes: 1

jonhid
jonhid

Reputation: 2125

That's it

  public static void main(String args[]){

     String fileNameOutput = "OutputFile.txt";
        String fileName = "InputWords.txt";

        Charset cs = Charset.defaultCharset() ;
        try (BufferedReader bReader = Files.newBufferedReader(Paths.get(fileName), cs)){

            PrintWriter outputStream = new PrintWriter(fileNameOutput); 
            int lineNum = 0;
            String line = null;

            while ( (line = bReader.readLine() ) != null ) {
               lineNum++;

                outputStream.println(line.split(" ")[0]);

            }
                outputStream.close();

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

}

Upvotes: 1

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Just use String#split(String) to split it where it encounter space. The result is an array. Choose the first index of the latter.

outputStream.println(line);

should be replaced with

outputStream.println(line.split(" ")[0]);

PS : For this to work if (line.split(" ").length > 1) continue; must be changed to allow Strings with more than one word.

Upvotes: 1

Related Questions