0

I am workig on a pretty neat problem challenge that involves reading words from a .txt file. The program must allow for ANY .txt file to be read, ergo the program cannot predict what words it will be dealing with.

Then, it takes the words and makes them their "Pig Latin" counterpart, and writes them into a new file. There are a lot more requirements to this problem but siffice to say, I have every part solved save one...when printng to the new file I am unable to perserve the line spacing. That is to say, if line 1 has 5 words and then there is a break and line 2 has 3 words and a break...the same must be true for the new file. As it stands now, it all works but all the converted words are all listed one after the other.

I am interested in learning this so I am OK if you all wish to play coy in your answers. Although I have been at this for 9 hours so "semi-coy" will be appreaciated as well :) Please pay close attention to the "while" statements in the code that is where the file IO action is happening. I am wondering if I need to utilize the nextLine() commands from the scanner and then make a string off that...then make substrings off the nextLine() string to convert the words one at a time. The substrings could be splits or tokens, or something else - I am unclear on this part and token attempts are giving me compiler arrors exceptions "java.util.NoSuchElementException" - I do not seem to understand the correct call for a split command. I tried something like String a = scan.nextLine() where "scan" is my scanner var. Then tried String b = a.split() no go. Anyway here is my code and see if you can figure out what I am missing.

Here is code and thank you very much in advance Java gods....

import java.util.*;
import javax.swing.*;
import java.io.*;
import java.text.*;

public class PigLatinTranslator
{
    static final String ay = "ay"; // "ay" is added to the end of every word in pig latin

    public static void main(String [] args) throws IOException
    {
        File nonPiggedFile = new File(...);
        String nonPiggedFileName = nonPiggedFile.getName();
        Scanner scan = new Scanner(nonPiggedFile);  

        nonPiggedFileName = ...;

        File pigLatinFile = new File(nonPiggedFileName + "-pigLatin.txt"); //references a file that may or may not exist yet

        pigLatinFile.createNewFile();
        FileWriter newPigLatinFile = new FileWriter(nonPiggedFileName + "-pigLatin.txt", true);
        PrintWriter PrintToPLF = new PrintWriter(newPigLatinFile);

        while (scan.hasNext()) 
        {
            boolean next;
            while (next = scan.hasNext()) 
            {
                 String nonPig = scan.next();
                 nonPig = nonPig.toLowerCase();
                 StringBuilder PigLatWord = new StringBuilder(nonPig);
                 PigLatWord.insert(nonPig.length(), nonPig.charAt(0) );
                 PigLatWord.insert(nonPig.length() + 1, ay);
                 PigLatWord.deleteCharAt(0);
                 String plw = PigLatWord.toString();

                 if (plw.contains("!") )
                 {
                     plw = plw.replace("!", "") + "!";
                 }

                 if (plw.contains(".") )
                 {
                     plw = plw.replace(".", "") + ".";
                 }

                 if (plw.contains("?") )
                 { 
                     plw = plw.replace("?", "") + "?"; 
                 }

                 PrintToPLF.print(plw + " ");
            }

            PrintToPLF.close();
        }
    }
}
James
  • 9,064
  • 3
  • 31
  • 49
reeltempting
  • 27
  • 1
  • 1
  • 7
  • http://stackoverflow.com/questions/6393260/java-parsing-text-file-and-preserving-line-breaks – James Nov 02 '12 at 01:16
  • And ..what is your question? If it is in there somewhere, add a '?' to the end. – Andrew Thompson Nov 02 '12 at 02:10
  • Sorry I suppose I thought my title said it all but since I am stuck on a solution then I am open to being wrong on the my perceived problem. Thequestions is how to I read words from a user submitted file and then alter those words, then print altered words to a new file....while...here is the main question...perserving the line breaks so all the words on line one stay on line one and words on line 2 from original doc go into new file on line 2 and so on. My code works but puts all new words one after another disregarding the line breask. – reeltempting Nov 02 '12 at 05:28
  • @reeltempting: Your code doesn't work. It doesn't handle two consonant words (i.e. "what") and vowel words (i.e. "about") correctly – durron597 Nov 02 '12 at 14:41
  • Just to add in an answer for the purpose of thos ewho may come later. The problem with the above code...at least as it relates to the question was tha I never should have gone with hasNext() - rather I should have read the file using NextLine() and grabbed the file one line at a time instead of one word at a time. – reeltempting Dec 09 '12 at 02:58

2 Answers2

1

Use BufferedReader, not Scanner. http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

I leave that part of it as an exercise for the original poster, it's easy once you know the right class to use! (And hopefully you learn something instead of copy-pasting my code).

Then pass the entire line into functions like this: (note this does not correctly handle quotes as it puts all non-apostrophe punctuation at the end of the word). Also it assumes that punctuation is supposed to go at the end of the word.

private static final String vowels = "AEIOUaeiou";
private static final String punct = ".,!?";

public static String pigifyLine(String oneLine) {
   StringBuilder pigified = new StringBuilder();
   boolean first = true;
   for (String word : oneLine.split(" ")) {
       if (!first) pigified.append(" ");
       pigified.append(pigify(word));
       first = false;
   }
   return pigified.toString();
}

public static String pigify(String oneWord) {
    char[] chars = oneWord.toCharArray();
    StringBuilder consonants = new StringBuilder();
    StringBuilder newWord = new StringBuilder();
    StringBuilder punctuation = new StringBuilder();
    boolean consDone = false; // set to true when the first consonant group is done

    for (int i = 0; i < chars.length; i++) {
        // consonant
        if (vowels.indexOf(chars[i]) == -1) {
            // punctuation
            if (punct.indexOf(chars[i]) > -1) {
                punctuation.append(chars[i]);
                consDone = true;
            } else {
                if (!consDone) { // we haven't found the consonants
                    consonants.append(chars[i]);
                } else {
                    newWord.append(chars[i]);
                }
            }
        } else {
            consDone = true;
            // vowel
            newWord.append(chars[i]);
        }
    }

    if (consonants.length() == 0) {
        // vowel words are "about" -> "aboutway"
        consonants.append("w");
    } 
    consonants.append("ay");

    return newWord.append(consonants).append(punctuation).toString();
}
durron597
  • 31,968
  • 17
  • 99
  • 158
0

You could try to store the count of words per line in a separate data structure, and use that as a guide for when to move on to the next line when writing the file.

I purposely made this semi-vague for you, but can elaborate on request.

dmarra
  • 853
  • 8
  • 23
  • Well in theory I would not know what was in the file. It is designed to change the words and spit them out. So if I didn't know what was in the file does your plan still work? We were allowed to assume no numbers are in the file and if they are, we just let the program change them like a word. – reeltempting Nov 02 '12 at 01:59
  • Sure it would. You would need to populate that list at the time of reading the file. I assume the words are separated by some delimiter (like a space), so you just read, record the word count of the line, piggify it, write it, next line. Basically, just keep track of the words on each line in some way while you read it. – dmarra Nov 02 '12 at 16:09