我应该编写一个程序来处理用户输入并将其翻译成Pig Latin并将其打印出来。我翻译为拉丁语的指示是:</ p>
Pig Latin是英语,最初的辅音移动到每个单词的末尾,然后是“ay”。以元音开头的单词只附加了“ay”。例如,短语 蘑菇蓝最深的阴影 在Pig Latin中有以下外观: e-Thay e-pey-day-ay ushroom-may ue-blay
所以我写了这个程序:
import java.util.Scanner;
public class Nothing
{
public static void main(String args[])
{
System.out.println("Enter sentence that has to be translated into Pig Latin ");
Scanner console = new Scanner(System.in);
String token = console.next();
String translated = processToken(token) + " ";
while(console.hasNext())
{
token = console.next();
translated = translated + processToken(token) + " ";
}
System.out.println(translated);
}
public static String processToken(String token)
{
String processed = "";
if(!(fC(token) == 'a' || fC(token) == 'e' || fC(token) == 'i' || fC(token) == 'o' || fC(token) == 'u' || fC(token) == 'y'))
{
if(fC(token) != 't')
{
processed = token.substring(1) + "-" + token.charAt(0) + "ay";
}
else
{
processed = token.substring(2) + "-" + token.substring(0, 2) + "ay";
}
}
else
{
processed = token + "-ay";
}
return processed;
}
public static char fC(String token) //returns first character in lowercase
{
return Character.toLowerCase(token.charAt(0));
}
}
并且它不起作用:(我输入输入并且它没有做任何事情:/我在扫描仪中使用简单的字符串而不是System.in测试它并且它工作。请帮助我!
答案 0 :(得分:2)
我认为正在等待额外的输入。已发送EOF信号,因为您的代码中没有其他终止逻辑。您可以在调试中运行它(在循环中使用断点来验证,
答案 1 :(得分:1)
您的代码可以正常工作,但如果您稍微调整一下它可以更好地工作,以便在输入时完全处理并打印每一行。我建议:
nextLine()
equals(...)
或equalsIgnoreCase(...)
进行退出测试,而不是==
。或者您可以使用contains(...)
e.g。
System.out.println("Enter sentence that has to be translated into Pig Latin ");
Scanner console = new Scanner(System.in);
while (console.hasNextLine()) {
String line = console.nextLine(); // get whole line
String[] tokens = line.split("\\s+"); // split it on whitespace
for (String token : tokens) {
// process and print out each token
System.out.print(processToken(token) + " ");
}
System.out.println(); // print out new line
// check if line contains "exit"
if (line.toLowerCase().contains(EXIT)) {
break;
}
}
if (console != null) {
console.close();
}
EXIT是public static String EXIT = "exit";