我的字符串反向程序问题

时间:2018-02-09 19:35:29

标签: java string

这里的新程序员,无法通过我的字符串逆转程序诊断问题。该程序应该比较两个字符串,并找出字符串x是否为字符串y的反转,如果是,则返回true,否则返回false。

public class Reverse
{
   public static void main(String[] args)
   {

      System.out.println(isExactReverse("ba", "a"));
      System.out.println(isExactReverse("desserts", "stressed"));
      System.out.println(isExactReverse("apple", "apple"));
      System.out.println(isExactReverse("regal", "lager"));
      System.out.println(isExactReverse("war", "raw"));
      System.out.println(isExactReverse("pal", "slap"));


   }
   public static boolean isExactReverse(String x, String y)
   {
      //To be completed
      int counter = 0;
      int temp = x.length() - 1;
      boolean result = false;

      for(int i = 0; i < y.length(); i++)
      {
         if(x.charAt(temp) == y.charAt(i))
         {
            counter++;
         }    
         temp--;
      }
      if(counter == y.length())
      {
        result = true; 
      }

    return result;
     }

}

我得到的输出不正确,我收到运行时错误。

true
true
false
true
true


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.charAt(String.java:658)
    at Reverse.isExactReverse(Reverse.java:24)
    at Reverse.main(Reverse.java:11)

预期产出:

False
True
False
True
True 
False

2 个答案:

答案 0 :(得分:4)

代码中的问题是它假定xy具有相同的长度。如果不是这样,代码会返回误报,如"ba" - "a"或崩溃,如"pal" - "slap"。< / p>

通过在isExactReverse方法的顶部添加此检查来解决此问题:

if (x.length() != y.length()) {
    return false;
}

Demo.

答案 1 :(得分:0)

代码当然可以编译。如果您能指定问题会很好。 但我猜你得到的结果是正确的。首先,我建议你简化代码。有很多台词,不必在那里。 这就是我要做的事。

public class Reverse
{
    public static void main(String[] args)
    {
        System.out.println(isExactReverse("ba", "a"));
        System.out.println(isExactReverse("desserts", "stressed"));
        System.out.println(isExactReverse("apple", "apple"));
        System.out.println(isExactReverse("regal", "lager"));
        System.out.println(isExactReverse("war", "raw"));
        System.out.println(isExactReverse("pal", "slap"));
    }

    public static boolean isExactReverse(String x, String y)
    {
        //To be completed
        int temp = x.length() - 1;
        boolean result = false;

        for(int i = 0; i < y.length(); i++)
        {
            if(!x.charAt(temp).equals(y.charAt(i)))
            {
                return false;
            }    

            temp--;
        }

        return true;
    }
}

这应该有效。我的帖子确实没有答案,因为我不知道你的问题,但这只是某种帮助,可能会解决你的问题。