检查给定字符串是否为回文时出错 [英] Error while checking whether a given string is palindrome or not

查看:91
本文介绍了检查给定字符串是否为回文时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常擅长c ++。最近我正在学习java。

但是我被困在这里并且不知道程序总是给我字符串是回文。



i am very good at c++. and recently i am learning java .
but i am stuck here and dont know how the program always gives me that the string is palindrome.

//here goes my code
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.Collections;
public class Test
{
	public static void display(ArrayList<Character> arr)
	{
		for(int i=0 ; i<arr.size() ; i++)
			System.out.print(arr.get(i) + " " );
		System.out.println();
	}
	public static boolean Check(ArrayList<Character> arr )
	{
		ArrayList<Character> temp = new ArrayList<Character>();
		temp = arr;
		Collections.reverse(temp);
		if(arr.equals(temp))
			return true;
		else
			return false;
	}
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		String name;
		System.out.println("enter the string");
		name = input.next();
		System.out.println(name.length());
		ArrayList<Character> arr = new ArrayList<Character>();
		for(int i=0 ; i<name.length() ; i++)
		{
			arr.add(name.charAt(i));
		}
		// it is always showing me that it is palindrome
		if(Check(arr))
			System.out.println("it is a palindrome");
		else
			System.out.println("it is not a palindrome");
	}
}





我的尝试:



必读:



看,我知道有很多更好的方法来做这件傻事。所以请不要建议我更好的实施。如果你能在这段代码中发现错误,我将非常感激。



谢谢。



What I have tried:

MUST READ:

See, i know that there are lot better ways to do this silly thing.So please don't suggest me a better implementation . I would be very thankful if you can find a error in this code.

Thanks.

推荐答案

在布尔检查功能中,您将arr分配给temp。 arr和temp是相同的对象。如果你逆转温度,你就会逆转。您最好看看如何克隆到对象,而不是赋值运算符
In your boolean check function you are assigning arr to temp. arr and temp are same objects. If you reverse temp, you are reversing arr. You better look at how to clone to an object, not the assignment operator


这篇关于检查给定字符串是否为回文时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆