✔ 最佳答案
比較簡單的方法是用StringBuffer的reverse( )
StringBuffer sb = new StringBuffer("hello");
System.out.println(sb.reverse()); // 會出「olleh」
System.out.println(sb.reverse().toString().equals("hello")); // 會出false
System.out.println(new StringBuffer("radar").reverse().toString().equals("radar")); // 出true
整個程式如下:
package hk.com.ahliu2.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = br.readLine();
System.out.println(
"The word you entered, '" + input + "' is" +
(new StringBuffer(input).reverse().toString().equals(input)
? ""
: " not") +
" a palindrome."
);
}
}
2010-05-05 12:03:54 補充:
boolean matched = true;
for(int i = 0; i < w.length(); i++) {
if(w.charAt(i) != w.charAt(w.length() - (i+1))) {
matched = false; // 只要有一個唔match就已經可以判斷唔係palindrome
break;
}
}
2010-05-05 12:04:09 補充:
if (matched) {
System.out.println("The word you entered, '" + w + "' is a palindrome.");
} else {
System.out.println("The word you entered, '" + w + "' is not a palindrome.");
}