判斷輸入的字符串是不是對(duì)稱的(charAt方法)
Posted on 2007-04-15 10:30 停留的風(fēng) 閱讀(1397) 評(píng)論(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)用法說明
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)
參數(shù)
strObj
必選項(xiàng)。任意 String 對(duì)象或文字。
index
必選項(xiàng)。想得到的字符的基于零的索引。有效值是 0 與字符串長(zhǎng)度減 1 之間的值。
說明
charAt 方法返回一個(gè)字符值,該字符位于指定索引位置。字符串中的第一個(gè)字符的索引為 0,第二個(gè)的索引為 1,等等。超出有效范圍的索引值返回空字符串。
示例
下面的示例說明了 charAt 方法的用法:
function charAtTest(n){ var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //
初始化變量。var s; //
聲名變量。s = str.charAt(n - 1); //
從索引為n – 1
的位置處//
獲取正確的字符。return(s); //
返回字符。 }