Results 1 to 2 of 2
Thread: Space Key
- 07-19-2012, 04:37 AM #1
Member
- Join Date
- Jul 2012
- Posts
- 1
- Rep Power
- 0
Space Key
I found a program online that converts the first character of each word in a string to uppercase. However, when I run it , the program only prints out the first word and then stops. Why does this happen? Here is the code.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String line; // Line of text entered by user.
Scanner scan = new Scanner(System.in);
System.out.println("Enter a line of text.");
line = scan.next();
System.out.println("Capitalized version:");
printCapitalized( line );
}
/**
* Print a copy of a string to standard output, with the first letter
* of each word in the string changed to upper case.
* @param str the string that is to be output in capitalized form
*/
static void printCapitalized( String str ) {
char ch; // One of the characters in str.
char prevCh; // The character that comes before ch in the string.
int i; // A position in str, from 0 to str.length()-1.
prevCh = '.'; // Prime the loop with any non-letter character.
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) )
System.out.print( Character.toUpperCase(ch) );
else
System.out.print( ch );
prevCh = ch; // prevCh for next iteration is ch.
}
System.out.println();
}
} // end CapitalizeOneString
Any help would be appreciated.
-
Re: Space Key
I think that you're wasting your time. Why play with a "found program" when you can simply and easily write your own better program? I wouldn't waste any time on found code that doesn't work but instead would work on my own code, and would sometimes study found code that works well and is written well (to study it and learn how to make my programs better).
Edit: oh well, despite what I just said, it's pretty easy to see why this current code works the way it does. The problem is evident in the main method alone. I will leave it as an exercise to the original poster to figure out why this program is behaving the way it's behaving. Again my hint: just look at the main method and walk through the code line by line, and then you''ll see the problem and its easy solution.Last edited by Fubarable; 07-19-2012 at 04:41 AM.
Similar Threads
-
Space Warrior - Multiplayer Space Shooter
By stes in forum Reviews / AdvertisingReplies: 2Last Post: 01-11-2012, 08:19 AM -
Space Invaders help!
By Midge in forum New To JavaReplies: 5Last Post: 03-04-2010, 04:38 PM -
add a space after 10 lines?
By ukemasta in forum New To JavaReplies: 10Last Post: 01-20-2010, 12:12 PM -
SWT Canvas drawing realtive to image space not canvas space.
By bobbie in forum SWT / JFaceReplies: 0Last Post: 07-05-2009, 12:31 PM -
space between images !!
By nhawlman in forum New To JavaReplies: 1Last Post: 01-09-2009, 11:17 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks