如何从字符串中获得一对字母? Java
问题描述:
所以我想获得一个方法来从字符串中获取两个字母,并使它们成为一对发送到另一个方法。这是我所拥有的:如何从字符串中获得一对字母? Java
public String encryptWord(String word) throws FileNotFoundException
{
String newWord = "";
String pair = "";
String extraLetter = "";
if(word.length() == 1)
{
extraLetter = word;
}
else
{
if(!extraLetter.equals(""))
{
if(word.length() % 2 != 0)
{
pair = extraLetter + word.substring(0, 1);
newWord += encryptTwo(pair);
for(int cntr = 0; cntr < word.length(); cntr++)
{
pair = word.substring(cntr, cntr + 1);
newWord += encryptTwo(pair);
}
}
else
{
System.out.println(extraLetter + " Hi");
pair = extraLetter + word.substring(0, 1);
newWord += encryptTwo(pair);
for(int cntr = 0; cntr < word.length() - 1; cntr++)
{
pair = word.substring(cntr, cntr + 1);
newWord += encryptTwo(pair);
}
pair = word.substring(word.length());
}
}
else
{
if(word.length() % 2 == 0)
{
for(int cntr = 0; cntr < word.length(); cntr++)
{
pair = word.substring(cntr, cntr + 1);
newWord += encryptTwo(pair);
}
}
}
}
return newWord;
}
该程序适用于所有单词,但单词中有奇数个字母。 这句话是: “这是一个测试,看看加密程序是否适用于这个程序”
任何帮助将是伟大的!谢谢!
答
if(!extraLetter.equals(""))
{
//this is never going to execute as `extraLetter` is set to ""
}
等代码只运行一个单词的偶数个字符。
+0
我刚刚意识到我的extraLetter变量在那里声明。它现在在顶部工作! – user3344862
尝试使用调试器或一些打印语句来查看程序中发生了什么。 – Christian
第二个'if'语句的内部永远不会运行。你能明白为什么吗? –