Assignment #86 and Letter at a Time
Code
/// Name: Ali Kurland
/// Period: 6
/// Program Name: Letter at a Time
/// File Name: LetterAtATime.java
/// Date Finished: 10/27/15
/// 1. The program runs and lists the characters, but then displays an "exception" message that the String index is out of the range.
/// 2. The length of the string variable "box" is three characters. The last character is at position 2.
/// 3. The loop repeats as long as i < message.length() instead of i<= message.length() because as long as i is less than the message
length, a character in any given position can be found, but when i is equal to the message length, there is no character in this position
that can be returned because the final character of the message is in a position equal to one less than the message length.
import java.util.Scanner;
public class LetterAtATime
{
public static void main( String[] args )
{
Scanner kb = new Scanner(System.in);
System.out.print("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + message.length() + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0) + "'.");
int lastpos = message.length() - 1;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i<message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int vowel_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I'|| letter == 'o' || letter == 'O'|| letter == 'u' || letter == 'U' )
{
vowel_count++;
}
}
System.out.println("\nYour message contains " + vowel_count + " vowels. Isn't that interesting?");
}
}
Picture of the output