程序错误

时间:2014-10-04 12:06:04

标签: java

//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;
    }

}

当我运行此代码时,它显示相同的输出。请指出错误。

2 个答案:

答案 0 :(得分:0)

目前还不清楚问题是什么,但你的for循环没有超过word中的字母,因为终止条件是基于传递给List的空buildAL大小方法。取代

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

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

答案 1 :(得分: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添加到列表中,或在word.length()循环中执行for

另外,如果我必须做同样的事情,我会做类似的事情 -

从扫描仪读取字符串后,只需执行

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.