Assignment #86 and LetterAtATime
Code
/// Name: Jason Kim
/// Period: 7
/// Program Name: LetterAtATime
/// File Name: LetterAtATime.java
/// Date Finished:12/1/15
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 a_count = 0, e_count = 0, i_count = 0, o_count = 0, u_count = 0;
for ( int i=0; i < message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' )
{
a_count++;
}
}
for ( int i=0; i < message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'e' || letter == 'E' )
{
e_count++;
}
}
for ( int i=0; i < message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'i' || letter == 'I' )
{
i_count++;
}
}
for ( int i=0; i < message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'o' || letter == 'O' )
{
o_count++;
}
}
for ( int i=0; i < message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'u' || letter == 'U' )
{
u_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
System.out.println("\nYour message contains the letter 'e' " + e_count + " times. Isn't that interesting?");
System.out.println("\nYour message contains the letter 'i' " + i_count + " times. Isn't that interesting?");
System.out.println("\nYour message contains the letter 'o' " + o_count + " times. Isn't that interesting?");
System.out.println("\nYour message contains the letter 'u' " + u_count + " times. Isn't that interesting?");
}
}
//String index out of range: 31
//the length of box is 3 but the position of the last character is 2
//Because the message lenght counts from 1 when there is a message and the charAt counts from 0, "i" exceeds the range of message.charAt() if we do i<=message.length().
Picture of the output