Search code examples
javareverse

How can I modify this code to insert random text into the console and it reverses it for me?


I'm very new to Programming and I've tried to use Integer.parseInt(args[0]); but it says that int cannot be converted to a String.

public class Reverse {

    public static void main (String[] args)
    {
        String s = "reverse this";
 
        for (int i = s.length() - 1; i >= 0; i--) {
            System.out.print(s.charAt(i));
        }
    }
}

Solution

  • You need a mechanism to input text from a source e.g. keyboard or command-line etc. Given below are some examples:

    From keyboard:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a text: ");
            String s = scanner.nextLine();
    
            for (int i = s.length() - 1; i >= 0; i--) {
                System.out.print(s.charAt(i));
            }
        }
    }
    

    A sample run:

    Enter a text: Hello World
    dlroW olleH
    

    From command-line:

    public class Main {
        public static void main(String[] args) {
            if (args.length >= 1) {
                for (int i = args[0].length() - 1; i >= 0; i--) {
                    System.out.print(args[0].charAt(i));
                }
            }
        }
    }
    

    You will have to run it as java Main "Hello World" where "Hello World" is the command-line argument.