2016-10-31 29 views
0

我是新來的java和我寫這種方法來輸入一個字符串單詞和輸出單詞向後拼寫。其意圖是創建的一種方法,而不是使用已有的方法,如簡單的反向。請幫助我指出如何做到這一點,以扭轉一個詞。我也試圖確定/計算是否有迴文。請幫忙!我已閱讀其他問題,但找不到足夠具體的案例。我知道我的代碼沒有運行,但我不確定如何解決它以獲得正確的輸出。書寫方法,拼寫單詞backwords和識別迴文數

一個例子是單詞「向後」去「sdrawkcab」。

public static int reverseWord(String word) { 
    int palindromes = 0; 

    for (int i = word.length(); i >= 0; i--) { 
     System.out.print(i); 
     word.equalsIgnoreCase(); 
       if (word.charAt(i)) == index(word.charAt(0 && 1))) { 
        palindromes++ 
          System.out.println(palindromes) 
       } 

    return i; 
    } 
    } 

回答

0

有你的代碼多個問題。

1.原型equalsIgnoreCase的是

public boolean equalsIgnoreCase(String str); 

所以這個方法期待一個字符串傳遞,但你不能沒有傳遞任何here.To解決這個問題,通過與要匹配您爲之另一個字符串這樣..

word.equalsIgnoreCase("myAnotherString"); 

2. word.charAt(i); 假設字= 「QWERTY」,所以索引每個字符無線的會是這樣

/* q w e r t y 
     0 1 2 3 4 5 */ 

所以,當你使用i = word.length();我會在6,因爲字長度的6.So word.charAt(i)將搜索字符在指數6,但因爲沒有指數6,它會返回一個異常ArrayIndexOutOfBound。要解決此問題,請啓動i from word.length()-1

3. if (word.charAt(i)); This extra ") ".Remove it

是Index()你自己的方法嗎?如果是,那就檢查一下。

0

下面的代碼打印輸入的字符串和檢查的反向,如果它是一個迴文

public static void main(String[] args) { 
     String input = "dad"; 
     char temp[] = input.toCharArray();//converting it to a array so that each character can be compared to the original string 
     char output[] = new char[temp.length];//taking another array of the same size as the input string 
     for (int i = temp.length - 1, j = 0; i >= 0; i--, j++) {//i variable for iterating through the input string and j variable for inserting data into output string. 
      System.out.print(temp[i]);//printing each variable of the input string in reverse order. 
      output[j] = temp[i];//inserting data into output string 
     } 
     System.out.println(String.valueOf(output)); 
     if (String.valueOf(output).equalsIgnoreCase(input)) {//comparing the output string with the input string for palindrome check 
      System.out.println("palindrome"); 
     } 
} 
0

因爲你什麼是你的代碼錯誤在這裏已經回答的問題是另一種方式,你可以通過使用一些概念,這有點不太低水平比字符數組直接合作做

public static boolean printWordAndCheckIfPalindrome(final String word) { 
    // Create a StringBuilder which helps when building a string 
    final StringBuilder reversedWordBuilder = new StringBuilder(""); 
    // Get a stream of the character values of the word 
    word.chars() 
      // Add each character to the beginning of the reversed word, 
      // example for "backwards": "b", "ab", "cab", "kcab", ... 
      .forEach(characterOfString -> reversedWordBuilder.insert(0, (char) characterOfString)); 
    // Generate a String out of the contents of the StringBuilder 
    final String reversedWord = reversedWordBuilder.toString(); 
    // print the reversed word 
    System.out.println(reversedWord); 
    // if the reversed word equals the given word it is a palindrome 
    return word.equals(reversedWord); 
}