Friday, February 6, 2015

BlueJ Program On Displaying Name With Surname First


In this program, user will enter any name including middle name and surname ( like Mohandas Karamchand Gandhi) and the output will be Gandhi Mohandas Karamchand.


This program can be done in different techniques. The first one is without using StringTokenizer or LastIndexOf() and substring () function.


import java.io.*;

class A
{
 String s1,s2="",w="";
 int i,len,sp=0;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 public void takeName() throws Exception
 {
  System.out.println("Enter the name:");
  s1=br.readLine();
  len=s1.length();
  for(i=0;i< len;i++)
  {
   if(s1.charAt(i)==' ')
   sp++;
  }
  for(i=0;i < len;i++)
  {
   if(sp!=0)
   s2=s2+s1.charAt(i);
   else
   w=w+s1.charAt(i);
   if(s1.charAt(i)==' ')
   sp--;
   }
   s2=w+" "+s2;
  System.out.println("Modified Name:"+s2);
  }
   public static void main(String args[])throws Exception
  {
   A ob=new A();
   ob.takeName();
   }
   }



   The same program using lastIndexOf () and substring () functions.



import java.io.*;

class A
{
 String s1,s2;
 int i;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 public void takeName() throws Exception
 {
  System.out.println("Enter the name:");
  s1=br.readLine();
  i=s1.lastIndexOf(' ');
  s2=s1.substring(i+1);
  s1=s1.substring(0,i);
  s1=s2+" " + s1;
  System.out.println("Modified Name:"+s1);
  }
   public static void main(String args[])throws Exception
  {
   A ob=new A();
   ob.takeName();
   }
   }


 The same program using StringTokenizer class.


  import java.util.*;

import java.io.*;
class A
{
 String s1;
 StringTokenizer stk;
 int i;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 public void takeName() throws Exception
 {
  System.out.println("Enter the name:");
  s1=br.readLine();
  stk=new StringTokenizer(s1);
  i=stk.countTokens();
  s1="";
  System.out.println("Number of tokens;"+i);
  while(stk.hasMoreTokens())
  {
  if(i!=1)
  s1=s1+ " " + stk.nextToken();
  else
   s1= stk.nextToken()+  s1;
   i--;
  }
    System.out.println("Modified Name:"+s1);
  }
   public static void main(String args[])throws Exception
  {
   A ob=new A();
   ob.takeName();
   }
   }



Related Post:  BlueJ Programs on String/Sentence

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner