2014-10-04 40 views
-5
//This program determines if the input string is a palindrome 
import java.util.*;//importing all the methods from java.util class 

import static java.lang.System.out; 
public class Pallindrome { 

    public static void main(String[] args) { 
     @SuppressWarnings("resource") 
     Scanner input= new Scanner(System.in); 
     String pallindrome; 
     out.println("Enter a string: "); 
     pallindrome= input.nextLine(); 
     ArrayList<String> pall= new ArrayList<String>(); 
     buildAL(pall, pallindrome); 
     display(pall); 
     if(isPalendrome(pall)) 
      out.println(pallindrome + " is a pallindrome"); 
     else 
      out.println(pallindrome + " is not a pallindrome"); 


    } 

    static void display(ArrayList<String> arr1){ //this method is for displaying the array list 
     for(int i=0; i<arr1.size();i++) 
      out.print(arr1.get(i)); 
     out.println(); 
     } 

    static void buildAL(ArrayList<String> arr2, String word){ //this is for building the array with the entered word 
     for(int i=0;i<arr2.size();i++) 
      arr2.add(word.charAt(i)+ ""); 

    } 

    static Boolean isPalendrome(ArrayList<String> arr3){ //it will test if the word is pallindrome 
     ArrayList<String> rarr3= new ArrayList<String>(); 
     rarr3.addAll(arr3); 
     Collections.reverse(rarr3); 
     for(int i=0;i<rarr3.size();i++) 
      if(!(rarr3.get(i).equals(arr3.get(i)))) 
       return false; 
     return true; 
    } 

} 

當我運行這段代碼時,它顯示了相同的輸出。請指出錯誤。程序錯誤

+1

您需要爲我們的錯誤告訴我們告訴你爲什麼,但是你知道'StringBuilder'有一個'reverse()'方法嗎?此外,這個詞是迴文。 – 2014-10-04 12:08:24

回答

0

目前還不清楚是什麼問題,但你的for循環犯規了在word字母作爲終止條件是基於空List大小傳遞給buildAL方法。更換

for (int i = 0; i < arr2.size(); i++) 

for (int i = 0; i < word.length(); i++) { 
0

下面

static void buildAL(ArrayList<String> arr2, String word){ 
for(int i=0;i<arr2.size();i++) 
    arr2.add(word.charAt(i)+ ""); 
} 

arr2.size()0因爲你沒有在列表中的任何元素。將word添加到列表中,或者在for循環中執行word.length()

另外,如果我必須做我會做這樣的事情同樣的事情 -

從掃描儀讀取字符串後,根本就

StringBuilder sb = new StringBuilder("your String"); 
if ("yourString".equals(sb.reverse().toString())) { 
    //or you can use equalsIgnoreCase also if that fits your requirement 
    //its a palindrome 
} //Otherwise, not.