JAVA 救助

2010-05-03 8:25 pm
Please enter a word: radar
The word you entered, 'radar' is a palindrome.



Please enter a word: abccba
The word you entered: 'abccba' is a palindrome.



Please enter a word: abcdecba
The word you entered: 'abcdecba' is not a palindrome.


請問用JAVA點先可以寫到 由左到右或者由右到左既次序都一樣, 好似上面D EXAMPLE咁

回答 (2)

2010-05-04 8:37 am
✔ 最佳答案
比較簡單的方法是用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.");
}
2010-05-03 11:26 pm
我比提示你啦
先accept 一個string
再計佢既長度係幾多
用 for loop 或者 while loop 同時由開頭同最尾
逐個逐個字母check


收錄日期: 2021-04-13 17:13:28
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20100503000051KK00397

檢視 Wayback Machine 備份