Write a program to input a sentence and convert it into uppercase and display each word in a separate line. Example: Input : India is my country Output : INDIA IS MY COUNTRY
Topic: Splitting a sentence into words
Answer
import java.util.Scanner;
class WordsInLines { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a sentence : "); String s = sc.nextLine();
s = s.toUpperCase() + " "; String word = ""; char ch;
for(int i = 0; i < s.length(); i++) { ch = s.charAt(i); if(ch == ' ') { if(word.length() > 0) System.out.println(word); word = ""; } else word = word + ch; } } }
The word-extraction pattern appears in this paper almost every year, so learn it as a template.
The method: build up characters into a word until a space is met, then print the word and reset it to empty.
The single most important line is s = s.toUpperCase() + " "; — adding a trailing space. Without it the LAST word never meets a space and is never printed, which is the classic bug in this question. Adding the space is far simpler than writing extra code after the loop.
The inner test if(word.length() > 0) guards against double spaces producing blank lines.
Convert to uppercase once, on the whole string, rather than character by character — shorter and clearer.
Use nextLine() to read the sentence; next() would read only the first word and the program would print nothing else.
s String - the sentence entered, in uppercase, with a trailing space word String - the word currently being built up ch char - holds each character of s in turn i int - loop variable, the index into the string sc Scanner - object used to read input