How to reverse the order of a sentence?

Asked

Viewed 111 times

1

I tried to make a program that takes a phrase and returns the phrase in reverse order. Example:

Input: "Hello, Java!";

Output: "Java! Hello,";

I tried to do it, but it’s not working.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String line1 = scanner.nextLine();
        String line2 = scanner.nextLine();
        String[] a = line1.split(",");
        
        for(int i=line1.length-1; i >= 0; i--);
            System.out.print(a[i] + " ");

        System.out.println(line1);
        System.out.println(line2);
    }
}
  • what’s going on?

1 answer

4


There are some mistakes there.

One of them has a ; in the for wrapping the block and not executing what you want to be repeated by causing a loose line to not even make sense because it uses a variable that only exists inside the loop.

It’s also picking up the size of line1 when your array is the a.

I don’t know what that line2 is doing there, I took, and I took the prints at the end because they do not seem necessary by the problem described.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line1 = scanner.nextLine();
        String[] a = line1.split(",");
        for (int i = a.length - 1; i >= 0; i--) System.out.print(a[i] + " ");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Got it !! Thank you very much.

  • @Matheusborba see on [tour] the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.