2014-09-24 45 views
1

我註釋掉了選項窗格以快速查看輸出結果。我不確定我在做什麼錯誤,並且我剛開始了計算機科學課。我的輸出與輸入相同,但我知道反向字符串方法是正確的,因爲我測試了它。反轉字符串,不起作用

import javax.swing.JOptionPane; 


public class ReverseString 
{ 
    public static void reverse(String n) 
    { 
    for(int i=0; i<n.length();i++) 
    { 
     n=n .substring(1, n.length()-i) 
     +n.substring(0,1) 
     +n.substring(n.length()-i, n.length()); 
    } 
    } 

    public static void main (String []arg) 
    { 
    String n = (JOptionPane.showInputDialog(null,"Input String to reverse")); 
    reverse(n); 
    System.out.println(n); 
    // JOptionPane.showInputDialog(null,"Reversed String is: "+Input); 
    } 
} 
+0

你什麼錯誤? 你也需要通過你的類名訪問你的反向函數 'ReverseString.reverse(n);' – 2014-09-24 01:01:30

+0

這工作正常! – 2014-09-24 01:04:25

+0

@ LJ_1102類名不是必需的,因爲這些方法是同一類的一部分,但有些會告訴你這是最佳實踐。 – LINEMAN78 2014-09-24 01:05:04

回答

1
public static void reverse(String n) 

您的返回類型爲void所以這個函數不返回任何東西,所以你不會有任何在您的控制檯反向 。

你爲什麼得到相同的結果? 因爲你只是把它打印出來由下列線

System.out.println(n); <-- you did not pass this n into your function. 
          Even though if you did, nothing would happened because 
          your reverse return type is void       

如果之後添加System.out.println(n);你的循環,你的代碼工作正常。

public static void reverse(String n) { 
     for (int i = 0; i < n.length(); i++) { 
      n = n.substring(1, n.length() - i) 
        + n.substring(0, 1) 
        + n.substring(n.length() - i, n.length()); 
     } 
     System.out.println(n); <---- print out the reverse result on the console 
            from the reverse function 
    } 

Read More About Returning a Value from a Method

+0

另外,一個更簡單的字符串反轉方法是'new StringBuilder(n).reverse()。toString()'。當前使用的方法會污染字符串池(不要指望初學者知道這一點,但所有Java開發人員最終應該學習的東西) – LINEMAN78 2014-09-24 01:13:44

+0

@ LINEMAN78我完全同意,但不要混淆操作比他或她更:) – 2014-09-24 01:14:31

+0

Yessss !!你太棒了!現在我只需要一個對話框,顯示沒有joptionspane輸入欄的新字符串.. – 2014-09-24 01:24:19