简体   繁体   English

爪哇检查回文

[英]Java- Check palindrome

Could someone please point out the mistake in my program? 有人可以指出我程序中的错误吗?

The output is always: "it is not a palindrome" 输出始终为:“这不是回文”

String newstr="";
for(int j=length-1;j>0;j--)
{
    char m=str.charAt(j);
    newstr=newstr+m;
}
if(newstr.equals(str) )
    System.out.println("it is a palindrome");
else
    System.out.println("it is not a palindrome");

thanks in advance:) 提前致谢:)

First of all, use String.equals() to compare Strings instead of == . 首先,使用String.equals()比较String而不是==

if(newstr.equals(str))

Also, string index start with 0, so you need: 另外,字符串索引以0开头,因此您需要:

for(int j=length-1;j>=0;j--)

Both fixes should work. 两种修复都应该起作用。

if(newstr==str)

should probably be 应该是

if ( newstr.equals( str ) )

And do read up on object comparison. 并仔细阅读对象比较。 You're effectively comparing two pointers, not the string contents. 您正在有效地比较两个指针,而不是字符串内容。

Of course, with Java 5 and onwards you could just do 当然,从Java 5开始,您可以

new StringBuilder( str ).reverse().toString().equals( str );

Cheers, 干杯,

index of array starts from 0. I guess you should use 数组的索引从0开始。我猜你应该使用

for(int j=length-1;j>=0;j--)

instead of 代替

for(int j=length-1;j>0;j--)

== operator check whether both the reference point to the same object or not. ==操作员检查两个参考点是否都指向同一对象。 .equals() method will actually check the content of the Strings. .equals()方法实际上将检查字符串的内容。

So your code must be 所以你的代码必须是

    if(newstr.equals(str))
    System.out.println("it is a palindrome");
    else
    System.out.println("it is not a palindrome");

== tests for reference equality. ==测试引用相等性。

.equals() tests for value equality. .equals()测试值是否相等。

Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object 因此,如果您实际上要测试两个字符串是否具有相同的值,则应使用.equals() (在少数情况下,可以保证具有相同值的两个字符串将由相同的对象表示)

This will be the final code. 这将是最终代码。 read about string comparison in java 阅读有关Java中的字符串比较的信息

  String newstr="";

   for(int j=length-1;j>0;j--)
   {
       char m=str.charAt(j);
       newstr=newstr+m;
    }
    if(newstr.equals( str ) )
    System.out.println("it is a palindrome");
    else
    System.out.println("it is not a palindrome");
public static boolean isPaliandrome(String str) {
        StringBuilder lettersBuff = new StringBuilder(str);
        String str_inverse = lettersBuff.reverse().toString();
        char[] charArrayInverse = str_inverse.toCharArray();
        boolean isPaliandrome = false;
        String caracInverseConverted = new String(charArrayInverse);
        if (str.equals(caracInverseConverted)) {
            isPaliandrome = true;
        }
        return isPaliandrome;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM