Reputation: 55
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
Upvotes: 0
Views: 123
Reputation: 347184
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);
Upvotes: 2