我再次启动代码后使用两种方法保存信息。我不明白为什么会这样,我不希望它这样做。我已经坚持了一段时间。任何帮助表示赞赏。 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 :(得分: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;
}
}