Reputation: 65
I commented out the options pane to get a quick view of the output..I'm not sure what I'm doing wrong and I just started a computer science class. My output is the same as the input but I know the reverse string method is correct because I tested it.
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);
}
}
Upvotes: 1
Views: 305
Reputation: 6739
public static void reverse(String n)
your return type is void
so this function does not return anything , so you will not have any reverse
in your console.
why you get the same result? because you just print it out by following line
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
if you add System.out.println(n);
after your for loop, your code works fine.
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
Upvotes: 1