这是我必须要合作的。我需要保留已经编写的内容,但我无法弄清楚hout使用循环和charAt()来查找回文。输入是在终端行中写入字符串所需的代码,因此我无法输入任何内容。有什么建议吗?
import java.io.*;
import java.util.*;
public class Palindrome
{
public static void main (String[] args) throws IOException
{
try // WE WILL TALK ABOUT EXCEPTIONS EVENTUALLY - JUST PUT ALL YOUR CODE IN THIS TRY BLOCK
{
// --------------------------------------------------------------------------------------------------------
if (args.length == 0)
{
System.out.println("FATAL ERROR: Must enter a word on the command line!\n");
System.exit(0);
}
String word = args[0];
boolean isPalindrome=true;
// --------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------
if (isPalindrome)
System.out.println( word + " IS a palindrome." );
else
System.out.println( word + " NOT a palindrome." );
}
catch ( Exception e )
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("EXCEPTION CAUGHT: " + sw.toString() );
System.exit( 0 );
}
} // END main
} //END CLASS Palindrome
答案 0 :(得分:1)
对于所有 i in 0..n/2
,请确保word[i] == word[someIndexThatDependsOnI]
true 。 (也就是说,如果任何 word[i] == word[someIndexThatDependsOnI]
false ,它就不是回文。使用适当的关键字可以在此时停止循环。)
我将someIndexThatDependsOnI
的发现留给读者,但它涉及字符串的大小......
答案 1 :(得分:0)
public bool isPalindrom(String word) {
for (int i = 0;i < word.length/2; i++) {
if (word.charAt(i) != word.charat(word.length - i - 1)) {
return false;
}
}
return true;
}
你必须检查编程错误,因为我现在没有现在的IDE
干杯