Computer Science, asked by maachodnewala998, 11 months ago

write a java program to input a sentence and extract each word of sentence and print them in separate line.
Example- I am xyz(input)
output--
I
Am
XYZ

Answers

Answered by QGP
14

Extracting Words - Java

We will first take user input of a string sentence using Scanner. The Scanner.nextLine() method will take the entire input. We will store it in a String type variable. Let's name it sentence.

To extract the words, we will first create a Scanner object out of the sentence variable which holds our user input string.

The Scanner separates tokens by a whitespace. Essentially, each word in the sentence is now a scanner token.

We will run a while loop using the Scanner.hasNext() test condition.

And, we will use the Scanner.next() method to print out the token, which in our case will be a word itself.

Using these Scanner methods, we can extract words out of a string and print out on a new line.

Here's the program code.

 \rule{320}{1}

Program Code - WordExtractor.java

import java.util.Scanner;   //Import Scanner

public class WordExtractor

{

   public static void main(String[] args)

   {

       //Create Scanner Object to take input

       Scanner sc = new Scanner(System.in);

       System.out.print("Enter a sentence: ");

       String sentence = sc.nextLine();    //Store input

       //Create another scanner object with sentence

       Scanner words = new Scanner(sentence);

       while(words.hasNext())

       {

           //Print each scanner token on new line

           System.out.println(words.next());

       }

   }

}

Attachments:
Answered by thapaavinitika6765
0

I am xyz(input) I am xyz(input) I am xyz(input) I am xyz(input)

Similar questions