string.length在java中无法正常工作 [英] string.length not working properly in java

查看:217
本文介绍了string.length在java中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个代码可以检查字符串是否是回文。代码是这样的:

Hi I have a code that checks if a string is palindrome or not.the code is like this:

         package ProjeTarahi;

         import java.util.*;
         import java.io.File;
         import java.io.FileInputStream;
         import java.io.FileNotFoundException;
         import java.util.Scanner;
         import java.util.logging.Level;
         import java.util.logging.Logger;
         import java.lang.String;

         public class Main 
         {

         public boolean CheckIsSymmetric(String s)
            {
               if (s.length()<=1) 
               {
                   return true;

                }

        if (s.charAt(0)==s.charAt(s.length()-1))
        {
            String sub = s.substring(1,s.length()-2);
            return CheckIsSymmetric(sub);
        }
        else
        {
            return false;
        }


    }

    public static void main(String args[])throws FileNotFoundException
    {
        Scanner sc=new Scanner(new FileInputStream(new File("in.txt")));
        String input=sc.nextLine();
        Main p=new Main();

        if(p.CheckIsSymmetric(input)==true)
        {
            System.out.println("in reshte motegharen ast");
        }
        else 
        {
            System.out.println("infinite");
        }

    }
}

我有在c#中编写了一个与上面的代码完全相同的代码,它的工作非常好,但它在java中不能正常工作,它的输出总是无限的。我跨过了我的代码,我认为问题出现在CheckSymmetric()的第一个if语句中,它总是会跳转但我不知道为什么。有人可以帮助我PLZ?

I have written a code in c# that is exactly the same as the code above and its working very well but its not working properly in java and its output is always infinite. I stepped over my code and i think the problem is in the first if-statement of the CheckSymmetric() and it always jumps it but i don't know why.anybody can help me plz?

推荐答案

public boolean checkIsSymmetric(String s) {
  return new StringBuilder(s).reverse().toString().equals(s);
}

保持简单并使用API​​。

Keep it simple and use the API.

这篇关于string.length在java中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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