KnowledgeBoat Logo

Computer Applications

Write a program in Java to accept a name containing three words and display the surname first, followed by the first and middle names.
Sample Input: MOHANDAS KARAMCHAND GANDHI
Sample Output: GANDHI MOHANDAS KARAMCHAND

Java

Java String Handling

154 Likes

Answer

import java.util.Scanner;

public class KboatSurnameFirst
{
    public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a name of 3 words:");
       String name = in.nextLine();
       
       /*
        * Get the last index
        * of space in the string
        */
       int lastSpaceIdx = name.lastIndexOf(' ');
       
       String surname = name.substring(lastSpaceIdx + 1);
       String initialName = name.substring(0, lastSpaceIdx);
       
       System.out.println(surname + " " + initialName);
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program in Java to accept a name containing three words and display the surname first, followed by the first and middle names. Sample Input: MOHANDAS KARAMCHAND GANDHI Sample Output: GANDHI MOHANDAS KARAMCHAND

Answered By

69 Likes


Related Questions