我应该编写一个程序,将整个短语转换为
pig latin.它应该从文件中读取短语,然后翻译并以猪拉丁语形式打印出来.
这必须从文件中读取文本.
键盘应该没有输入.
这是我的示例文件文本:
This is a test
Here is a second line
and a third
输出应该是原始短语,然后是猪拉丁语版本.两个版本都应该在输出中用引号括起来.
“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 “
我已经改变了一些东西,现在我可以输出一个句子,但不能超过一个.我如何获得多行输出.如何让扫描仪进入下一行?
我现在拥有以下内容:
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
}
}
在拉丁语中输出“这是一个测试”是“is-Thay is-way a-way est-tay”
最佳答案 你在这里只读一个字:
Scanner words = new Scanner(line);
String word = words.next();
String pigLatin = pigLatinWord(word);
试试这个:
Scanner words = new Scanner(line);
String pigLatin = "";
while(words.hasNext()){
String word = words.next();
pigLatin += pigLatinWord(word) + " ";
}
如果您对字符串连接有所了解,请在此处使用StringBuilder.