2015-09-09 21 views
0

我再次啓動代碼後使用的兩種方法都會保存信息。我不明白爲什麼這會繼續發生,我不希望它這樣做。我一直堅持這一點。任何幫助表示讚賞。 Thanks.EDIT:這應該是反轉一個字符串。我不想使用StringBuffer或類似的東西。另外我想用一種方法來扭轉它,無論它是否是無效與我無關。爲什麼我輸入的內容始終保存?

import java.util.Scanner; 

public class ReverseThree { 

static Scanner input = new Scanner(System.in); 
static String a = "", b = "", c = ""; 
static int i = 0; 

public static void main(String[] args) { 
    do { 
     System.out.print("Enter Words: "); 
     a = input.nextLine(); 

     reverseMethod(); 
     //reverseMethod(a); 
     System.out.println("Reverse: " + b); 

     System.out.print("Try Again?"); 
     c = input.nextLine(); 
    } while (c.equalsIgnoreCase("YES")); 
}// end main 

/* 
* public static String reverseMethod(String a) { 
* for (i = a.length() - 1; i>= 0; i--) 
*  b = b + a.charAt(i); return a; 
*} 
*/ 

public static void reverseMethod() { 
    for (i = a.length() - 1; i >= 0; i--) 
     b = b + a.charAt(i); 
} 

}//end class 
+0

你的問題是缺少了很多細節:請放多一點說明這個代碼做什麼,什麼是應該做的,更多關於它究竟是如何不工作的權利?請不要強迫我們猜測。請查看[提問](http://stackoverflow.com/help/asking)上的[help]部分,瞭解如何改進此問題 –

+0

.......謝謝。 –

回答

2

保存信息?那是因爲他們是這個班級的領域。試試這個:

public static void reverseMethod() { 
    b = ""; 
    for (i = a.length() - 1; i >= 0; i--) 
     b = b + a.charAt(i); 
} 

順便說一句,除非確實需要,否則引入這樣的類變量並不好。這是更好的:

import java.util.Scanner; 

public class ReverseThree { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     String c; 
     do { 
      System.out.print("Enter Words: "); 
      String a = input.nextLine(); 

      String b = reverseMethod(a); 
      System.out.println("Reverse: " + b); 

      System.out.print("Try Again?"); 
      c = input.nextLine(); 
     } while (c.equalsIgnoreCase("YES")); 
     input.close(); 
    } 

    public static String reverseMethod(String a) { 
     String b = ""; 
     for (i = a.length() - 1; i >= 0; i--) 
      b = b + a.charAt(i); 
     return b; 
    } 

} 
+0

這爲什麼解決這個問題?它爲我工作,但我不明白爲什麼。你能否解釋或指出我自己尋找信息的方向? – Alei

相關問題