-2

q1:write a program to print following output from given input=

input: aaa bbb ccc ddd eee fff ggg hhh iii jjj

output: bbb aaa ddd ccc fff eee hhh ggg jjj iii

SOLUTION:

package practice;

import java.io.*;
import java.util.*;

public class happy {
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        String t;
        String arr[]=new String[n];
        for(int i=0;i<n;i++)
        {
            arr[i]=in.nextLine();
            t=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=t;
        }
        System.out.println(arr);
    }
}

where did i went wrong can anybody please provide solution in java?

Felk
  • 7,720
  • 2
  • 35
  • 65
Amar
  • 7
  • 3
  • You want to swap adjacent elements or blocks of adjacent elements, divided by space? Can you present what you got and what you expected instead? – Mathias Bader Sep 15 '17 at 15:34
  • [Ljava.lang.String;@55f96302 sir i got this in my console as output.i want to swap adjacent elements – Amar Sep 15 '17 at 16:05
  • `arr` is an array and you can't print arrays with `System.out.println` - that's why you get `[Ljava.lang.String;@55f96302`. You need `System.out.println(Arrays.toString(arr))`. – DodgyCodeException Sep 15 '17 at 16:22

1 Answers1

-1

Take the input string a split it using using the Java split() method and store the output into a String array. From there it becomes easy.

 Scanner scanner = new Scanner(System.in);
 String [] inputArr = scanner.nextLine().split(" ");
 for(int i = 0; i < inputArr.length; i++)
 {
    if( ( i+1 ) % 2 == 0 )
    {
        String temp = inputArr[i-1];
        inputArr[i-1] = inputArr[i];
        inputArr[i] = temp;
    }
 }

You're working in pairs of two's. The pairs can be easily checked by using the modulus of the current element (adding 1 to it because of the way indexing works). When the if-statement triggers (when there is no remainder), it simply swaps the two elements.

You could also probably use a built-in method, so check the Java Documentation at https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html if you'd like a more cleaner and perhaps more efficient way of doing this.

Lord Why
  • 14
  • 6