0

My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}

An example input:

4
1 2 3 4

Expected output:

4 3 2 1
5
  • 1
    Don't you need to populate your array before you attempt to go over it in reverse order? Commented Jun 7, 2017 at 2:54
  • yes I do by using the Scanner input --> arr[arr_i] = in.nextInt(); Commented Jun 7, 2017 at 2:55
  • I think you missed my point... What is the end goal here? Commented Jun 7, 2017 at 2:56
  • Could you give an example of the input and output? Commented Jun 7, 2017 at 3:56
  • @cricket_007 the end goal is to print the received input in reverse. Commented Jun 7, 2017 at 4:00

5 Answers 5

4

Use a StringBuilder and always insert at 0 index.

See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)

StringBuilder bld = new StringBuilder();

for (int arr_i = 0; arr_i < n; arr_i++) {
    int i = in.nextInt();
    bld.insert(0, i);
}

System.out.println(bld.toString());
Sign up to request clarification or add additional context in comments.

4 Comments

This code doesn't print a blank space after inserting a number. I tried adding bld.insert (0, " "); but this doesn't fulfill the requirement because there shouldn't be an empty space after the last number.
Just use docs.oracle.com/javase/7/docs/api/java/lang/… to delete the last char
Of course there are for loops being used inside of each StringBuilder.insert(...) call.
As OP Posted My question is if there's any way to improve my code
2

The simplest approach I found is to use String Builder here:

Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
   stringBuilder.append(in.next());
   if(in.hasNext()) {
     stringBuilder.append(" ");
   }
}

System.out.print(stringBuilder.reverse());

4 Comments

That's still 2 loops.
Updated my answer for more simple solution with one loop
@Gray this is doing fine. Why do you think its not reversed? As mentioned in question with an example Input: 1 2 3 4 Output is: 4 3 2 1
Missed the reverse @Ms.Zia. Sorry.
1

First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,

Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
        .collect(Collectors.joining(" ")));

Comments

1

I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.

public static void main(String[] args) {
    System in = new Scanner(System.in);
    int n = in.nextInt();
    String allNumbers = "";

    for (int i = 0; i < n; i++) {
        int current = in.nextInt();
        allNumbers = current + " " + allNumbers;
    }

    if(allNumbers != ""){
      allNumbers = allNumbers.substring(0,allNumbers.length()-1);
    }

    System.out.println(allNumbers);
}

2 Comments

better to use a StringBuilder as per my answer
@Scary Wombat Yeah you're right. I think this method will result in an extra blank character (" ") at the end of the string.
-1

Java has inbuilt String method for the same. If your input is a String, you can use the below-

String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen

1 Comment

Question isn't completely reversing a string (you missed the spaces)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.