Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to solve the following problem but how do write the method that accepts String as an argument?

Write a method named printReverse that accepts a String as an argument and prints the characters in the opposite order. If the empty string is passed as an argument, the method should produce no output. Be sure to write a main method that convincingly demonstrates your program in action. Do not use the reverse method of the StringBuilder or StringBuffer class!

So far I have solved it in a easier manner:

import java.util.Scanner;

class ReverseString {
    public static void main(String args[]) {
        String original, reverse = "";
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string to reverse");
        original = in.nextLine();

        int length = original.length();

        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + original.charAt(i);

        System.out.println("Reverse of entered string is: " + reverse);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

I highly recommend you to go through a basic tutorial.

You can simply do:

private static String myReverse(String str) {
    String reverse = "";
    int length = str.length();
    for( int i = length - 1 ; i >= 0 ; i-- ) {
       reverse = reverse + str.charAt(i);
    }
    return reverse;
}

And in your main, you simply:

String reversed = myReverse(in.nextLine());

Note that the method is static because you're referring to it from a static manner (main method). If you don't want it to be static, you'll have to access it via an object.

Also note that it's a good practice to always have curly brackets for for loops, even if it contains a single line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...