Posted on 2007-04-15 10:30
停留的風 閱讀(1397)
評論(0) 編輯 收藏 所屬分類:
Java程序集合
import javax.swing.JOptionPane;
public class CheckPalindrome
{
public static void main(String[] args)
{
String s=JOptionPane.showInputDialog(null,"Enter a string ","Example",JOptionPane.QUESTION_MESSAGE);
String output="";
if(isPalindrome(s))
{
output=s+" is a palindrome!";
}
else
output=s+" is not a palindrome!";
JOptionPane.showMessageDialog(null,output,"The result",JOptionPane.INFORMATION_MESSAGE);
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
low++;
high--;
}
return true;
}
}
//////////////////////////////////////////////////////////////////
charAt(index)用法說明
返回指定索引位置處的字符。
strObj.charAt(index)
參數
strObj
必選項。任意 String 對象或文字。
index
必選項。想得到的字符的基于零的索引。有效值是 0 與字符串長度減 1 之間的值。
說明
charAt 方法返回一個字符值,該字符位于指定索引位置。字符串中的第一個字符的索引為 0,第二個的索引為 1,等等。超出有效范圍的索引值返回空字符串。
示例
下面的示例說明了 charAt 方法的用法:
function charAtTest(n){
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //
初始化變量。
var s; //
聲名變量。
s = str.charAt(n - 1); //
從索引為n – 1
的位置處
//
獲取正確的字符。
return(s); //
返回字符。
}