Program opened below. You can scroll through the algorithm, Java code and output.
Program 78
Snowball String
Question
A snowball string has words arranged so their lengths increase by exactly one from each word to the next. Accept a sentence and determine whether it is a snowball string.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input the sentence and remove the final punctuation.
Step 4: Validate the input values and display an error message if they are outside the permitted range.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Split the sentence into words.
Step 7: Set previousLength=0.
Step 8: For each word, compare its length with previousLength+1.
Step 9: If any length differs, mark the sentence as not snowball.
Step 10: Update previousLength after each word.
Step 11: Display SNOWBALL STRING or NOT A SNOWBALL STRING.
Step 12: Stop.
Java program
Javaimport java.util.*;
class SnowballString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim().replaceAll("[.?!]$", "");
String[] words = s.split("\\s+");
boolean ok = true;
for (int i = 1; i < words.length; i++) {
if (words[i].length() != words[i - 1].length() + 1) {
ok = false;
}
}
System.out.println(ok ? "SNOWBALL STRING" : "NOT A SNOWBALL STRING");
}
}Sample output
Input: I am the Lord
Output:
SNOWBALL STRING