Java while loop check palindromes

Question

A string is a palindrome if it reads the same forward and backward.

The words "mom", "dad", "level" and "noon" are all palindromes.

Write a program that prompts the user to enter a string

Report whether the string is a palindrome.

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      // Create a Scanner
      Scanner input = new Scanner(System.in);
      // Prompt the user to enter a string
      System.out.print("Enter a string: ");
      String s = input.nextLine();

      //your code here
   }/*w  ww .  j  av  a 2 s.  c om*/
}




import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      // Create a Scanner
      Scanner input = new Scanner(System.in);
      // Prompt the user to enter a string
      System.out.print("Enter a string: ");
      String s = input.nextLine();

      // The index of the first character in the string
      int low = 0;

      // The index of the last character in the string
      int high = s.length() - 1;

      boolean isPalindrome = true;
      while (low < high) {
         if (s.charAt(low) != s.charAt(high)) {
            isPalindrome = false;
            break;
         }
         low++;
         high--;
      }
     if (isPalindrome)
         System.out.println(s + " is a palindrome");
      else
         System.out.println(s + " is not a palindrome");
   }
}



PreviousNext

Related