5-5 Location
Post date: Apr 3, 2014 11:06:58 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;
}
}