-4

We want to create a "Greeting Counter" that tell us how many times you entered a greeting. Improve the program that takes any number of words in a single line as input, and outputs the number of greetings. Valid greetings to count are "Hi", "Hello" and "Hey". Different cases are allowed. The input ends with -1 on a line alone.

Ex: If the input is:

Hi World Hey -1

then the output is:

Greetings: 2
import java.util.Scanner;

public class GreetCounter {

    public static void main(String[] args) {

     Scanner scnr = new Scanner(System.in);

     String input = scnr.nextLine();
     int i = 1;
      
      while(!input.equals("-1")) {
         if (input.equals("Hi") || input.equals("Hello") || input.equals("Hey")) {
             i +=0; 
         }
      }
         System.out.print("Greetings: ");
         System.out.println(i);
    }
}
Pengasus
  • 1
  • 1

1 Answers1

0

Below code will work like this: Enter the sentence How are you Hello Hey hello Output will be Greetings : 3

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Geetings {
    public static void main(String[] args) throws IOException {
    /*taking input from console*/
        String input = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        if (line.equals("-1"))
            br.close();
        else
            input = line;   
        /* finding frequency of greeting */
        String[] arr = input.split(" ");
        int counter = 0;
        for (String str : arr) {
            if (str.equalsIgnoreCase("Hi") || str.equalsIgnoreCase("Hello") || str.equalsIgnoreCase("Hey")) {
                counter++;
            }
        }
        System.out.println("Greetings : "+counter);
    }
}
Rajnish
  • 58
  • 5