Need help on java H/w. Thanks Write a program that allows the user to enter a St
ID: 3807446 • Letter: N
Question
Need help on java H/w. Thanks
Write a program that allows the user to enter a String and then uses a for loop to check whether the String is a, which means that if you reverse the order of the characters in the String you get the same String back. The program should output, String is a palindrome or not. This program and lots of code exists on the Internet. Please write a short paragraph explaining how your program works above your source code. Attach Snipping photos of source code and output. For example: Please Enter a string: noon noon is a palindrome//Output Please Enter a string: abcdcba is a palindrome//Output Please Enter a string: cat is not a palindrome//OutputExplanation / Answer
PalindromeOrNot.java
import java.util.Scanner;
public class PalindromeOrNot {
public static void main(String[] args) {
// Declaring variables
String str = "", revStr = "";
boolean bool;
// Scanner Class Object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
// Getting the string entered by the user
System.out.print("Please Enter a String :");
str = sc.next();
// Calling the method by passing the string as input.
bool = testPalindrome(str);
// based on the bool value the corresponding message will be displayed
if (bool) {
System.out.println(str+" is a Palindrome.");
} else {
System.out.println(str+" is not a Palindrome.");
}
}
/*
* This method will check whether the string is palindrome or not If the
* String is Palindrome then it returns true If not,It returns false
* Param:string return: boolean
*/
private static boolean testPalindrome(String str) {
// Declaring local variables
String revstr = "";
int count = 0;
// This for loop will reverse the string
for (int i = 0; i < str.length(); i++) {
revstr += str.charAt((str.length() - 1) - i);
}
/*
* This for loop will compare each character in the user entered string
* and the reversed string
*/
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != revstr.charAt(i))
return false;
}
return true;
}
}
__________________
Output:
Please Enter a String :noon
noon is a Palindrome.
__________________
Output2:
Please Enter a String :abcdcba
abcdcba is a Palindrome.
_________________
Output3:
Please Enter a String :cat
cat is not a Palindrome.
________________
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.