我注释掉了选项 Pane 以快速查看输出。我不确定我做错了什么,我刚刚开始上计算机科学类(class)。我的输出与输入相同,但我知道反向字符串方法是正确的,因为我测试了它。
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);
}
}
最佳答案
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
如果您在 for 循环后添加 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
}
关于java - 反转字符串,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006827/