troubleshooting Question

Core Java. Swaping first and last words in sentence. Bug

Avatar of SunnyX
SunnyX asked on
JavaJava EE
7 Comments2 Solutions3483 ViewsLast Modified:
I would like to make a piece of code that swap first and last words in sentence. I come up with some solution as you can see below. However, the program doesn't work well. Please help me to find mistake. You code will be much appreciated !
input : "London is the capital of UK"
Output : "UK is the capital of UK London "

Should be :
input : "London is the capital of UK"
Output : "UK is the capital of London "

Looking forwards for help from you dear Experts !

package TaskCh;
//import java.util.Scanner;

public class TaskCh {

	public static void main(String[] args) {
	   //  System.out.println("Enter line of text.");
	   // Scanner kb = new Scanner(;
	    String s = "London is the capital of UK" ;  // kb.nextLine(); // Read the whole line instead of word by word
	    System.out.println("Original line is  : ");
	    String[] words = s.split("\\s+"); // Split on any whitespace

	    if (words.length > 1) { 
	    	// Swap first and last words  	
	        s = words[words.length-1] + " " +  s.substring(s.indexOf(words[1], words[0].length() -2 )) + " " + words[0].toLowerCase();

	        s = s.substring(0, 1).toUpperCase() + s.substring(1); // 


	    System.out.println("\n\n\nModified line is :");

Information Technology Specialist

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros