簡體   English   中英

我的字符串反向程序出現問題

[英]Issue with my string reverse program

較新的程序員,無法診斷我的字符串反轉程序的問題。 該程序應該比較兩個字符串,並找出字符串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

您的代碼中的問題是它假定xy的長度相同。 如果不是這樣,則代碼將返回假陽性(例如"ba" - "a" )或崩潰(例如"pal" - "slap"

通過在isExactReverse方法的頂部添加此檢查來解決此問題:

if (x.length() != y.length()) {
    return 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 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;
    }
}

這應該工作。 對於您的帖子,我真的沒有答案,因為我不知道您的問題,但這只是某種幫助,可能會解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM