java - 反转字符串,不起作用

标签 java string methods reverse

我注释掉了选项 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 
    }

Read More About Returning a Value from a Method

关于java - 反转字符串,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006827/

相关文章:

java - 将 gradle 子项目链接到任务

java - 声明 LinkedBlockingQueue<String> 时出现 NullPointer 异常

java - Endpoints Frameworks 2.0 迁移后 Endpoint Api 调用错误

java - 无法在 NetBeans 中构建我的项目,我正在使用 Glassfish Server。每次运行时都会出现错误,模块尚未部署

swift - 带有字符串插值的属性字符串不起作用(swift)

连接多个字符串?

python - 为什么 2.__add__(3) 在 Python 中不起作用?

java - 插入二维字符串数组时出现空指针异常

mysql - 查找哈希中特定列的总和

python - 当在前一个循环中找到某个字符时,如何开始新的循环?