0

I am writing code that will capitalize every word of a sentence. My problem is that my code only outputs the first word of a sentence capitalized and ignores the remaining words.

import java.util.Scanner;

public class CapitalString {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);        

    System.out.println("Enter a line of text:");
    String line = scan.next();  
    System.out.println();
    System.out.println("Capitalized version:");
    printCapitalized( line );

    scan.close(); 
}

static void printCapitalized( String line ) {
    char ch;       
    char prevCh;   
    int i;         
    prevCh = '.';  

    for ( i = 0;  i < line.length();  i++ ) {
        ch = line.charAt(i);
        if ( Character.isLetter(ch)  &&  ! Character.isLetter(prevCh) )
            System.out.print( Character.toUpperCase(ch) );
        else
            System.out.print( ch );
        prevCh = ch;  

    }
    System.out.println();
}

}

Actual Output:

Enter a line of text: testing this code

Capitalized version: Testing

Expected Output:

Enter a line of text: testing this code

Capitalized version: Testing This Code

cscscs
  • 55
  • 7
  • The "cheat" way? Split the `String` and possibly use a `StringBuilder` or `StringJoiner` – MadProgrammer Nov 23 '19 at 02:51
  • 3
    Your actual problem is `String line = scan.next();`, which will scan all the text up to the next white space. Use `scan.nextLine()` instead – MadProgrammer Nov 23 '19 at 02:52
  • 2
    Do not close a scanner tied to `System.in`. You are not responsible for closing that. It is the JVMs job to do that. Closing it results in nobody being able to use System.in anymore. – Zabuzard Nov 23 '19 at 02:59
  • 1
    Does this answer your question? [How to capitalize the first character of each word in a string](https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string) – Farzad Vertigo Nov 23 '19 at 02:59

1 Answers1

2

Your actual problem is

String line = scan.next();

which will scan all the text up to the next white space.

Use scan.nextLine() instead

System.out.println("Enter a line of text:");
String line = scan.nextLine();
System.out.println();
System.out.println("Capitalized version:");
printCapitalized(line);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366