我需要编写for循环来迭代字符串对象(嵌套在String[]数组中),以便使用以下条件对该字符串中的每个字符进行操作。
每次我尝试使用不同的循环和不同的策略/实现时,我都会以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。
发布于 2014-11-20 05:49:20
假设问题是StringIndexOutOfBoundsException,那么发生这种情况的唯一方法就是当其中一个words是空字符串时。了解这一点也提供了解决方案:当长度为零的if\else以不同的方式处理特殊情况时,执行一些不同的操作( words \ else)。这是这样做的一种方法:
if (!"".equals(words)) {
// your logic goes here
}另一种方法是在循环中(当您有一个循环时)简单地这样做:
if ("".equals(words)) continue;
// Then rest of your logic goes here如果不是这种情况或问题,那么线索就在于您没有向我们展示的代码部分(毕竟,在这种情况下,您没有给我们提供相关的代码)。最好提供一个完整的代码子集,可以用来复制问题(testcase)和完整的异常(所以我们甚至不必自己尝试。
https://stackoverflow.com/questions/27031896
复制相似问题