Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Input in Java

Chapter 6

Input in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Correct Spacing in a Line of Text


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.

import java.util.Scanner;

 

public class CorrectSpacing {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        // Read input line

        System.out.print("Enter a line of text: ");

        String input = sc.nextLine();

 

        // Remove extra spaces

        String output = input.trim().replaceAll("\\s+", " ");

 

        // Display result

        System.out.println("\nCorrectly spaced line:");

        System.out.println(output);

 

        sc.close();

    }

}

Output

 
SAMPLE INPUT : 
Enter a line of text:
   Java     programming     is     powerful   

SAMPLE OUTPUT : 
Correctly spaced line:
Java programming is powerful

Explanation

1. trim()

    • Removes leading and trailing spaces.
2. replaceAll("\\s+", " ")
    • \\s+ matches one or more whitespace characters (spaces, tabs, etc.)
    • Replaces them with a single space
3. The final output:
    • Has no space before the first word
    • Has exactly one space between adjacent words