2014-10-04 72 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.