program to find middle name eg rakesh kumar rathod so the output will be kumar .. bt tokeniser
Here is an example of StringTokenizer class that accept the full name from the user and display the middle name.
import java.util.*; public class GetMiddleName { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your full name: "); String fullName = input.nextLine(); StringTokenizer stok = new StringTokenizer(fullName); String firstName = stok.nextToken(); StringBuilder middleName = new StringBuilder(); String lastName = stok.nextToken(); while (stok.hasMoreTokens()) { middleName.append(lastName + " "); lastName = stok.nextToken(); } System.out.println("Middle Name: "+middleName.toString().trim()); } }
The given code also displays the middle name by accepting the full name from the user.
import java.util.*; public class GetMiddleName { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your full name: "); String fullName = input.nextLine(); int firstSpace = fullName.indexOf(" "); int lastSpace = fullName.lastIndexOf(" "); String middleName = fullName.substring(firstSpace,lastSpace); System.out.println("Middle Name: "+middleName); } }
Ads