English

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 GANDHISample output: - Computer Applications

Advertisements
Advertisements

Question

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 

Code Writing

Solution

import java.util.*; 
public class SQ4 
{public static void main(String j[]) 
{String s; 
int p = 0; 
Scanner sn = new Scanner(System.in); 
System.out.println("Enter a name"); 
s = ' ' + sn.nextLine(); 
p = s.lastIndexOf(' '); 
System.out.print(s.substring(p + 1)); // from this position till end of the string
System.out.print(s.substring(0, p)); // starting position till p( excluding) 
}} 
shaalaa.com
  Is there an error in this question or solution?
Chapter 4: String Handling - EXERCISES [Page 290]

APPEARS IN

Avichal Computer Applications [English] Class 10 ICSE
Chapter 4 String Handling
EXERCISES | Q IX. 4. | Page 290
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×