Comparing Chars of String and The Use of Nested while Loops in Java Using Eclipse IDE: Palindrome Checker Example

in #utopian-io7 years ago (edited)

What Will I Learn?

In this tutorial;

  • You will learn the use of nested while loops.
  • You will learn the use of the equalsIgnoreCase method.
  • You will learn to how to compare and get the characters of the string.
  • You will learn how to get the length of the string.

Requirements

  • Java SE Development Kit (Not necessarily the last version) is required.
  • Eclipse IDE or any similar Interated Development Enviroment (IDE) that is designed for Java programming language is required.

Difficulty

  • Intermediate

Tutorial Contents

The purpose of this tutorial is to show the usage of the nested while loops in Java. A palindrome checker program is implemented for this purpose. A word that reads the same backward and forward called as palindrome. For example, "radar" is a palindrome since reading backward and forward is same. For this program, we have single java file (Palindrome_Checker.java).

code.JPG

The program will ask the word to the user. Therefore we need the Scanner class.

import java.util.Scanner;

In this program, two different string variables is neccessary. One of these strings is for the word which is going to be entered by the user and the other one is for the reserved string which gives another trial in program to the user. Note that "Y" is chosen as reserved string for another trial.

        String word, repeat="Y";

In addition to string variables, two integer variables are also neccessary. One of these integers is for the left index position of the word and the other one is for the right index position of the word. Note that the character at the left index position and the character at the right index position will be compared in the program.

        int left_index, right_index;

Now, the scanner can be defined.

        Scanner scan = new Scanner(System.in);
Nested while Loops

A nested loop contains another loop inside of the outer loop. The inner loop executes for each iteration of the outer loop. In this program, the outer while loop will be to controle the number of trial. So the outer while loop will contain the whole program's single trial. In each iteration of the outer while loop a single test happens. The inner while loop will be for the index incrementation.

The equalsIgnoreCase Method

The equalsIgnoreCase method allows to ignore the lowercase and uppercase diffrences in the string. If we use this method in the outer while loop, the user can enter "Y" or "y" string to continue.

        while(repeat.equalsIgnoreCase("y")) {

The program needs to ask the word to the user firstly. It can be achieved with the following code;

            System.out.println("Enter the word:");
            word = scan.nextLine();

Befored the comparing characters, the left index should be the index number of the first character of the string which is zero and the right index should be the index number of the last character of the string which is String.length()-1. Note that the index of the first character is 0 and last character is length of the string minus one (1).

            left_index=0;
            right_index=word.length()-1;
Comparing The Strings

The charAt method allows user to get the character at the given index of the string. The inner while loop compares the chars in this program. In the inner while loop, the purpose is increamenting the left index and decrementing the right index if the characters at both indexes are same and left index is smaller than the right index.

            while (word.charAt(left_index)==word.charAt(right_index) && left_index<right_index) {
                left_index++;
                right_index--;
            }

Thus, when the execution of inner while loop is finished, the string is palindrome if and only if the left index is greater than equal to right index value. The string is not a palindrome if the incremetation of left index and decrementation of right index are not enough to satisfy the right index < left index condition (In other words the entire string is not tested because the character at the right index is not equal to character at left index.) . If at the end of the inner while loop the right index < left index condition is satisfied, this means that whole string is tested and the string is palindrome.

            if (right_index>left_index)
                System.out.println("NOT PALINDROME");
            else
                System.out.println("PALIDROME");

At the end of the outer while loop, the feedback for the another trial needs to be taken with the following code.

            System.out.println("Check another word (y/n)?");
            repeat = scan.nextLine();

If the user enters "y" or "Y" the compiler executes outer while loop again. If the user enters other than "y" or "Y", program ends.

Results

When the program runs, the user asks the word that will be checked by the program to the user.
r1.JPG

r2.JPG

If you enter "palindrome" as input to the system, the system says its not palindrome as it is expected. Then, system ask "Check another word (y/n)?"

r3.JPG

r4.JPG

If you enter "y", the system again asks the word that will be checked by the program.

r5.JPG

r6.JPG

If you enter "radar" as input to the system, the system says its palindrome as it is expected

r7.JPG

r8.JPG

Lastly, if you enter "n" as an answer to the "Check another word (y/n)?" question, the program ends.

r9.JPG

r10.JPG

Code of The Program
import java.util.Scanner;
public class Palindrome_Checker {
    public static void main(String[] args) {
        String word, repeat="Y";
        int left_index, right_index;
        Scanner scan = new Scanner(System.in);
        while(repeat.equalsIgnoreCase("y")) {
            System.out.println("Enter the word:");
            word = scan.nextLine();
            left_index=0;
            right_index=word.length()-1;
            while (word.charAt(left_index)==word.charAt(right_index) && left_index<right_index) {
                left_index++;
                right_index--;
            }
            if (right_index>left_index)
                System.out.println("NOT PALINDROME");
            else
                System.out.println("PALIDROME");
            System.out.println("Check another word (y/n)?");
            repeat = scan.nextLine();
        }
    }
}
Github

You can get this program here.
github.JPG

Curriculum

You can find my other java related tutorials in below links.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

I love these post.
Its sure going to help my Java coding

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @aromatheraphy I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations @aromatheraphy! You received a personal award!

1 Year on Steemit

Click here to view your Board

Do not miss the last post from @steemitboard:

Christmas Challenge - The party continues

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @aromatheraphy! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.22
TRX 0.26
JST 0.040
BTC 98487.39
ETH 3469.86
USDT 1.00
SBD 3.23