【问题标题】:Reversing a string, not working反转字符串,不起作用
【发布时间】:2014-09-24 00:49:22
【问题描述】:

我注释掉了选项窗格以快速查看输出。我不确定我做错了什么,我刚刚开始了计算机科学课程。我的输出与输入相同,但我知道反向字符串方法是正确的,因为我对其进行了测试。

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);
  }
}

【问题讨论】:

  • 你得到什么错误?您还需要通过您的类名ReverseString.reverse(n); 访问您的反向功能
  • 这工作正常!
  • @LJ_1102 类名不是必需的,因为方法是同一个类的一部分,但有些人会告诉你这是最佳实践。
  • 如果我在对话框中输入“REVERSE”,我会得到“REVERSE”作为我的字符串,而不是“ESREVER”
  • @LINEMAN78 你是对的,我虽然类是在main 定义上定义的,但缩进失败......

标签: java string methods reverse


【解决方案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                          

如果您在 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

【讨论】:

  • 另外,一个更简单的反转字符串的方法是new StringBuilder(n).reverse().toString()。当前使用的方法污染了字符串池(不要指望初学者知道这一点,但所有Java开发人员最终都应该学习的东西)
  • @LINEMAN78 我完全同意,但不要让操作人员比他或她更容易混淆 :)
  • @KickButtowski 同意,但是我想指出一点,因为即使是很多专业的 Java 开发人员也没有意识到这一点,因为 1.5 编译器中添加了保护(在将字符串附加到循环)。
  • @Cpt.Awesome 您需要将反向消息的结果存储回 n。 n = reverse(n)。原始的“n”对象没有被修改,因为字符串是不可变的,Java 是按值传递的(更准确地说,对象引用是按值传递的)。
猜你喜欢
  • 2022-11-06
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
相关资源
最近更新 更多