193k views
5 votes
Write a program that will ask the user to input a phrase (multiple word sentence), and an integer value. A static function will be created that takes the sentence (string) and integer as input parameters and returns a single word (string) of that sentence. If the integer was the number three, then the word returned would be the third word in the sentence. If the integer given in zero or negative, simply return an empty string. (do not let it crash) If the integer given is higher than the number of words in the sentence, then just return the last word.

User Frederik H
by
4.4k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step 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

Write a program that will ask the user to input a phrase (multiple word sentence), and-example-1
User Jamie Aden
by
4.4k points