Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the entries the person typed that end in "im" in java?

Tags:

java

I want to count the entries(Strings) written in console that end in "im", so how can I do it as a starter?

import java.lang.String; 
import java.util.Scanner;

public class WordCount {
    public static void main (String[]args){

        final String SENTINEL = "END";
        Scanner sc = new Scanner(System.in);
        String text = "xy";

        do {
            System.out.print("Type a text or type "+SENTINEL+" when you are done. ");
            text = sc.nextLine();
            } while(!text.equalsIgnoreCase(SENTINEL));

            boolean IMcheck = text.endsWith("im");
            int count = 0;
            if(IMcheck == true){
                count++;
            }
            System.out.println("You have typed "+ count +" texts that end in \"im\" ");
        } 
    }
like image 813
Altin Mullaidrizi Avatar asked Feb 02 '26 20:02

Altin Mullaidrizi


1 Answers

As the commenters have said, you need to move your if-statement inside the do-while loop. Having the variable "IMcheck" is unnecessary here.

To solve the issue, I've put the code you used to assign the "IMcheck" variable inside your if-statement, and I've moved it into your do-while loop.

public class WordCount {

   public static void main (String[]args) {
      final String SENTINEL = "END";
      int count = 0;
      Scanner sc = new Scanner(System.in);
      String text = "xy";

   do {
         if(text.endsWith("im"))
            count++;

         System.out.print("Type a text or type "+SENTINEL+" when you are done. ");
         text = sc.nextLine();

   } while(!text.equalsIgnoreCase(SENTINEL));

   System.out.println("You have typed "+ count +" texts that end in \"im\" ");
   }
}
like image 149
LuminousNutria Avatar answered Feb 05 '26 08:02

LuminousNutria