Answer:
See explaination
Explanation:
import java.util.Scanner;
public class Word
{
public static void main(String args[])
{
Scanner read=new Scanner(System.in);
char repeat='Y';
String phrase=null;
int index=0;
while(repeat=='Y')
{
System.out.println("enter a phrase :");
phrase=read.nextLine();
while(index<=0)
{
System.out.println("enter an index greater than 0");
index=Integer.parseInt(read.nextLine());
}
String s;
int spaces = phrase == null ? 0 : phrase.length() - phrase.replace(" ", "").length();
int numofwords=spaces+1;
if(index>numofwords)
{
index=numofwords;
}
System.out.println("word is: "+ getWord(phrase,index));
System.out.println("do you want to repeat (Y/N)");
repeat=read.nextLine().charAt(0);
index=0;
}
read.close();
}
private static String getWord(String phrase, int index) {
// TODO Auto-generated method stub
Scanner in =new Scanner(phrase);
String word=null;
int wordindex=0;
while(wordindex!=index)
{
word=in.next();
wordindex++;
}
in.close();
return word;
}
}
Check attachment screenshot