Java Program to print even length words in a String
Welcome! In this tutorial, we will learn how to develop a Java program to print even length words in a string entered by the user. So, let’s start with the code:
import java.util.Scanner; class second { public static void main(String ar[]) { Scanner sc=new Scanner(System.in); String st; st=sc.nextLine(); String w[]=st.split(""); //split the entire string into individual character int count=0,j=0; String words[]=st.split(" "); //split the entire string into individual words for(int i=0;i<w.length;i++) { if(w[i].equals("")||w[i].equals(" ")) //will be true when a word ends { if(count!=0 && count%2==0) //checking whether the word ended contain even no. of words or not { System.out.println(words[j++]); //if contains then print that word } else { j++; //if the ended word doesn't contain even no. of words then skip that word count=0; //set count=0 for next word } } else { count+=1; } } } }
First, let’s take input from the user using Scanner class
For this, we need to import Scanner using the Java import keyword. After that, a new object sc of Scanner class is declared. Then, nextLine() method is used to take input from the user and stored it in the String st.
Now, we will print even length words
To store each individual character in the given string, create an array of string named w. I will also create another array of string named words that will store individual words in the given string. I will also need two integer variable count for counting the no. of characters in every individual word and variable j that keep counting of words in array words. Set count=0 and j=0.
Now, the loop begins and will keep iterating until array length of w. Then we will check whether the ith character in the string is empty space or not if it is then it may be the ending of a word. Then we will check if count>0 or not if it is then we will check whether the length of scanned word is even or not if it is even then print the word. If the length of word is not even then skip that word and set count=0. Then, increment j by 1.
Also, read: Java String endsWith() Method
If the scanned character is not an empty space then increment count by 1. So, now our code is ready. Let’s run it and check the output.
Input:
this is a boy and my car name is jacky
Output:
this is my name is
Leave a Reply