Java Notes Prev: Java Example: Console: Take me to your leader
Java Example: Console: Capitalize
This program reads a word, makes the first letter upper case and the remainder lower case, and outputs it. The input-process-output organization is very common in simple programs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// File : examples1-sequential/CapitalizeConsole.java // Purpose: Capitalize first letter and make remainder lower case. // Uses String methods: substring, toUpperCase, toLowerCase. // Author : Fred Swartz - 27 Mar 2007 - Placed in public domain. import java.util.*; public class CapitalizeConsole { public static void main(String[] args) { //.. Create and initialize a scanner to read from the console. Scanner in = new Scanner(System.in); //.. Input a word System.out.println("Enter a word"); String inputWord = in.next(); // Reads one "word" //.. Process - Separate word into parts, change case, put together. String firstLetter = inputWord.substring(0,1); // Get first letter String remainder = inputWord.substring(1); // Get remainder of word. String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase(); //.. Output the result. System.out.println(capitalized); } } |
Where to declare local variables: at beginning or at first use?
Local variables can be declared anywhere before they are used. There are two styles of declaration.
- Declaring variables when they are first used. This style has several advantages:
- It guarantees that variables are initialized.
- No unused variables are declared.
- It's clear what the type is at the time it is used.
- The distance between variable uses is small, which makes it easier on the human reader.
- Declare at the front. Advantages:
- This leaves space on the remainder of the line to add a comment. Comments sometimes don't fit on the remainder of the line so they must be put on the line before if required, but good variable names often mean that comments are not as important.
- It lists the "cast of characters" at the front, which some programmers find helpful.
Clarity first. Use whichever style makes the program clearer for you, or whichever style your instructor requires. Most of my programs use the declare-at-first-use style.