22.5k views
2 votes
Write a void method called palindromeCheck that takes NO argument. The method should have functionality to check whether or not the word is a palindrome and print to the screen all of the palindromes, one per line. Also, the last line of the output should have the message: "There are x palindromes out of y words provided by user" (where x is the number of palindrome words detected, and y is the total number of words entered by user). Hint: for this lab exercise you will need the following methods on String objects: length() gives the length of a string (that is, the number of characters it contains) and charAt(i) - gives the character at position i.

User Dilshod
by
5.1k points

2 Answers

3 votes

Final answer:

To write the palindromeCheck method, split the input string into individual words, iterate over each word to check if it is a palindrome, and print the results.

Step-by-step explanation:

To write the palindromeCheck method, you can follow these steps:

  1. Take input from the user, which is the word(s) they want to check for palindromes.
  2. Split the input string into individual words using the split method.
  3. Initialize two counters, palindromeCount and wordCount, to keep track of the number of palindrome words and total number of words entered, respectively.
  4. Iterate over each word in the array of input words.
  5. Inside the loop, create a boolean variable isPalindrome and set it to true.
  6. Use a for loop to compare characters at each end of the word.
  7. If any characters do not match, set isPalindrome to false and break out of the loop.
  8. If isPalindrome is still true after the loop, print the word as a palindrome and increment palindromeCount by 1.
  9. Increment wordCount by 1 regardless of whether the word is a palindrome or not.
  10. After the loop, print the final message stating the number of palindrome words (palindromeCount) out of the total number of words entered (wordCount).

User Adam Monsen
by
5.1k points
1 vote

Answer:

Step-by-step explanation:

import java.util.Scanner;

public class PalindromeCheck

{

public static void palindromeCheck()

{

String someWord=" ";

int count=0;

int total=0;

System.out.println("Ënter some words entered by whitespace");

Scanner keyboard =new Scanner(System.in);

String[] words=keyboard.nextLine().split(" ");

for(int i=0;i<words.length;i++)

{

boolean flag=true;

int l=words[i].length();

for(int j=0;j<=l/2;j++)

{

if(words[i].charAt(j)!=words[i].charAt(l-j-1))

{

flag=false;

break;

}

}

if(flag)

count++;

}

System.out.println("There are "+count+" palindromes out of "+words.length+" words");

keyboard.close();

}

public static void main(String[] args)

{

palindromeCheck();

}

}

Output

Ënter some words entered by whitespace

This is a malayalam.

There are 3 palindromes out of 4 words

User Chidinma
by
5.2k points