【发布时间】:2015-01-17 20:37:57
【问题描述】:
我需要编写 for 循环来遍历 String 对象(嵌套在 String[] 数组中)以使用以下条件对该字符串中的每个字符进行操作。
- 首先,在字符串中添加一个连字符
- 如果该字符不是元音,则将该字符添加到字符串的末尾,然后将其从字符串的开头删除。
- 如果字符是元音,则在字符串末尾添加“v”。
每次我尝试使用各种循环和各种策略/实现时,我都会以某种方式结束StringIndexOutOfBoundsException 错误。
有什么想法吗?
更新:这里是所有代码。我不需要程序的其余部分的帮助,只是这部分。但是,我知道您必须看到系统在工作。
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
此外,这里是从中提取文本的示例文件(我们跳过了第一行):
2
你今天好吗
这个例子有数字 1234
【问题讨论】:
-
最好显示代码
-
@PSR,我已经添加了相关的代码块。此外,您可以看到我已将
words.substring(1, words.length())作为占位符放置,直到我可以得到一个有效的循环。我需要这个来测试操作是否正确。 -
@user3072758 相关代码是怎样的?你为什么打电话给
trim()并丢弃结果?您是否忘记将transWord分配回数组?transWord是什么?你期望什么输出,你会得到什么? -
trim()被调用来削减字符串末尾的空间。transWord继续包含我们迄今为止操作过的所有单词,并且是最终的完整字符串,将与所有修改一起输出给用户。 -
当您调用
trim()时,它不会就地操作String(String是不可变的)。相反,它返回一个新的String实例。你还没有给我们一个示例输入和(期望的)输出。