kmlepley
kmlepley

Reputation: 41

I need to convert a sentence into pig latin using an input file

I am supposed to write a program that converts entire phrases into pig latin. It should read in phrases from a file, and then translate and print out in pig latin form.

This must read in text from a file. There should be NO input from the keyboard.

This is my sample file text:

This is a test

Here is a second line

and a third

The output should be the original phrase followed by its pig latin version. Both versions should be surrounded by quotes in the output.

"This is a test" in pig latin is "is-Thay is-way a-way est-tay "

"Here is a second line" in pig latin is "ere-Hay is-way a-way econd-say ine-lay "

"and a third" in pig latin is "and-way a-way ird-thay "

I have changed a few things and now I can output a sentence but not more than one. How would I get more than one line of output. How would I get the scanner to go to the next line?

What I have now is the following:

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

public class pigLatin2 {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("phrases.txt"));

        while (input.hasNextLine()) {
            String line = input.nextLine();
            System.out.print("\"" + line + "\"" + " in pig latin is \"");
            Scanner words = new Scanner(line);
            while (words.hasNext()) {
                String word = words.next();
                String pigLatin = pigLatinWord(word);
                System.out.print(pigLatin + " ");
            }
            System.out.println("\"");
        }
    }


    public static String pigLatinWord(String s) {
        String pigWord;
        if (isVowel(s.charAt(0))) {
            pigWord = s + "-way";
        } else if (s.startsWith("th") || s.startsWith("Th")) {      // or (s.toUpperCase().startsWith("TH"))
            pigWord = s.substring(2) + "-" + s.substring(0,2) + "ay";
        } else {
            pigWord = s.substring(1,s.length()) + "-" + s.charAt(0) + "ay";
        }
        return pigWord;
    }


    public static boolean isVowel(char c) {
        String vowels = "aeiouAEIOU";
        return (vowels.indexOf(c) >= 0);    // when index of c in vowels is not -1, c is a vowel
    }
}

which outputs, "This is a test" in pig latin is "is-Thay is-way a-way est-tay "

Upvotes: 4

Views: 3338

Answers (1)

maskacovnik
maskacovnik

Reputation: 3084

You are reading just one word here:

    Scanner words = new Scanner(line);
    String word = words.next();
    String pigLatin = pigLatinWord(word);

Try this:

    Scanner words = new Scanner(line);
    String pigLatin = "";
    while(words.hasNext()){
        String word = words.next();
        pigLatin += pigLatinWord(word) + " ";
    }

If you know something about string concatenating, use StringBuilder here instead.

Upvotes: 2

Related Questions