ICSE Class 10 Computer Applications Question 22 of 32

Input in Java — Question 22

Back to all questions
22
Question

Question 22

Write a Java program that reads a line of text separated by any number of whitespaces and outputs the line with correct spacing, that is, the output has no space before the first word and exactly one space between each pair of adjacent words.

Answer
import java.util.Scanner;

public class KboatCorrectSpacing
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        while(in.hasNext()) {
            String w = in.next();
            System.out.print(w + " ");
        }
        in.close();
    }
}
Output
BlueJ output of KboatCorrectSpacing.java