I'm creating a program that needs to read multiple lines of text from user input and display the number of times each letter from the alphabet is seen in the string. The last line ends with a period, which will serve as a sentinel value. This is what I have so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LetterCounter
{
public static void main(String[] args)
{
try {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String lineOfText;
char letter, choice;
int countArray[] = new int[26];
do
{
System.out.println("Enter the String (Ends with .):");
while ((lineOfText = input.readLine()) != null)
{
for (int i = 0; i < lineOfText.length(); i++)
{
letter = lineOfText.charAt(i);
int index = getIndex(letter);
if (index != -1)
{
countArray[index]++;
}
}
if (lineOfText.contains("."))
break;
}
System.out.println("Count Alphabets:");
for (int i = 0; i < countArray.length; i++)
{
System.out.println((char) (65 + i) + " : " + countArray[i]);
}
//Ask user whether to continue or not
System.out.println("\nWould you like to repeat this task? (Press y to continue or n to exit program): ");
choice = input.readLine().toLowerCase().charAt(0);
System.out.println();
} while (choice == 'y');
}
catch (IOException e)
{
// Auto-generated catch block
e.printStackTrace();
}
}
//method to get the index of alphabet
public static int getIndex(char letter)
{
if (Character.isAlphabetic(letter))
{
if (Character.isUpperCase(letter))
{
return (int) letter - 65;
}
else
{
return (int) letter - 97;
}
}
else
{
return -1;
}
}
}
I was wondering how I would allow multiple lines of text. So for I can do one line.