Snowball String Program in Java | ISC Computer Science 2024 Paper 2

A snowball string is a sentence where each word is arranged in ascending order of their length and is also consecutive.

For example “I am the Lord” is a snowball string as
Length of word ‘I’ is 1
Length of word ‘am’ is 2
Length of word ‘the’ is 3
Length of word ‘Lord’ is 4
The length of each word is one more than the previous word. Hence they are consecutive and in ascending order.

Write a program to enter any sentence and check if it is a snowball string or not. The words in the sentence may be separated by one or more spaces and terminated by ‘.’ or ‘?’ only. The program will generate appropriate error message for any other terminating character.

Test your program for the following data and some random data:

Example 1
INPUT: He may give bonus.
OUTOUT: IT IS A SNOWBALL STRING

Example 2
INPUT: Is the cold water frozen?
OUTPUT: IT IS A SNOWBALL STRING

Example 3
INPUT: Look before you leap.
OUTPUT: IT IS NOT A SNOWBALL STRING

Example 4
INPUT: The child is father of the man!
OUTPUT: INCORRECT TERMINATING CHARACTER. INVALID INPUT

import java.util.Scanner;
class Snowball{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = in.nextLine();
        char last = s.charAt(s.length() - 1);
        if(last != '.' && last != '?'){
            System.out.println("INCORRECT TERMINATING CHARACTER. INVALID INPUT");
            return;
        }
        int len = 0;
        String word = "";
        boolean status = true;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetterOrDigit(ch))
                word += ch;
            else{
                if(len == 0)
                    len = word.length();
                else if(len + 1 != word.length()){
                    status = false;
                    break;
                }
                else
                    len = word.length();
                word = "";
            }
        }
        if(status)
            System.out.println("IT IS A SNOWBALL STRING");
        else
            System.out.println("IT IS NOT A SNOWBALL STRING");
    }
}