In: Computer Science
An alliteration is a stylistic device in which successive words begin with the same letter (or sometimes the same sound). In our case we will only consider alliterations that follow the "same letter" property. It is often the case that short words (three letters or less) are inserted to make the sentence make sense. Here are some examples of alliterations:
alliteration's artful aid
Peter parker's poems are pretty
Round the rugged rock the ragged rascal ran
Peter Piper picked a peck of pickled peppers
Your program will ignore words that are three letters or less when searching for alliterations. For this program, you may assume that the first word of the sentence is at least 4 letters long. For this part of your lab, you will write a java program that asks the user to enter a sentence, word or phrase, and respond by telling the user if the input is an alliteration.
An example of your program's interactions are shown below:
ALLITERATION DETECTOR
ease enter a sentence: Peter parker's poems are pretty
Your input was: "Peter parker's poems are pretty"
The input is an alliteration
ALLITERATION DETECTOR
Please enter a sentence: Able was I ere I saw Elba
Your input was: "Able was I ere I saw Elba"
The input is not an alliteration
The approach to solve the problem is as follows:
Java program:
import java.util.Scanner;
class Main{
public static void main(String args[]){
//object to input from keyboard
Scanner sc = new Scanner(System.in);
System.out.println("ALLITERATION DETECTOR");
//input string from user
System.out.print("Please enter a sentence:");
String text = sc.nextLine();
//display the input
System.out.println("Your input was:" + text);
//the first letter of first word
char check = text.charAt(0);
//set alliteration to true
boolean alliteration = true;
//split the string into array
String data[] = text.split(" ");
//traverse all words
for(int i=0;i<data.length;i++){
//if the letter does not match and the word length is 4 or greater
//set alliteration to false and break
if (data[i].charAt(0) != check && data[i].length() >= 4 )
{
alliteration = false;
break;
}
}
//if alliteration is true
if(alliteration){
System.out.println("The input is an alliteration. ");
}
//alliteration is false
else {
System.out.println("The input is not an alliteration. ");
}
}
}
Snippet of code