Thursday, April 26, 2018

Program to show the need of startsWith() method of String class.

Program to show the need of startsWith() method of String class.

import java.util.Scanner;

public class StringAssignment01
{
    public static void main(String[] args)
    {
        try
        {
            // take a paragraph and store names saprated by comma
            // there shoud be no space before or after the comma
            String paragraph = "naman,manoj,kamal,rakesh,aman,nimesh,maniram"
                    + ",arif,raju,kunti,rajesh";
          
            System.out.println("Names["+paragraph+"]\n");
          
            // split the paragraph, jahan jahan bhi comma aaye
            String[] names = paragraph.split(",");
          
            Scanner sc = new Scanner(System.in);
          
            // agar flag ki value false hogi toh hum loop ko terminate kar denge
            boolean flag = true;
          
            // start infinite loop
            while(flag)
            {
            System.out.print("Enter a name (type .. to exit the loop) ->");
            String text = sc.next();
          
            // fetch all the names from the the array
            for(int i = 0;i < names.length; i++)
            {
                // check if ith element of array starts with given text
                if(names[i].startsWith(text))
                {
                    // print that element of array
                    System.out.println(names[i]);
                }
              
            }
          
            // agar input  dot dot (..) hai toh flag me false daal dou
            // jis se hum loop ke bahar ja saken
            if(text.equals(".."))
            {
                flag = false;
            }
          
            } // end of main
        }  // end of class
        catch (Exception e)
        {
            e.printStackTrace();
        }
      
        System.out.println("# end of application #");
    }
}

No comments:

Post a Comment