5-5 Location

posted Apr 3, 2014, 4:06 AM by Dlovan ismail   [ updated Apr 7, 2014, 7:30 AM ]
//Write a program to find location of given word in a sentence using function

package location;
import java.util.Scanner;

public class Location 
{
        public static void main(String[] args) 
        {
            Scanner scan=new Scanner(System.in);

            System.out.print("Enter a sentence : ");
            String s=scan.nextLine();

            System.out.print("Enter a word : ");
            String w=scan.next();

            int index=Find(s, w);

            if(index!=-1)  
            System.out.println("Location of given word ="+index);
            else
            System.out.println("The word is not found in a sentence");  

        }  

        public static int Find(String s,String w)
        {
            Scanner scan=new Scanner(s);
            int L=0,flag=0;

            while(scan.hasNext())
            {
                L++;
                
                if(scan.next().compareTo(w)==0)
                    {
                      flag=1;
                      break;
                    }

            }

            return(flag==1)?L:-1;

        }
}

ċ
Location.java
(1k)
Dlovan ismail,
Apr 3, 2014, 4:06 AM
Comments