Task 1- Write a program that allows the user to enter a String and then uses a f
ID: 3572319 • Letter: T
Question
Task 1- Write a program that allows the user to enter a String and then uses a for loop to check whether the String is a palindrome, 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 is a common program and lots of code exists on the Internet. Please right 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 //Output
Explanation / Answer
StringPalindrome.java
public class StringPalindrome {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.print("Please Enter a string: ");
String str = in.nextLine();
boolean status = isPalindrome(str);
if(status){
System.out.println(str+" is a palindrome");
}
else{
System.out.println(str+" is not a palindrome");
}
}
public static boolean isPalindrome(String str){
// if length is 0 or 1 then String is palindrome
if(str.length() == 0 || str.length() == 1)
return true;
for(int i=0; i<str.length()/2; i++){
/*checking each character from front and back both are same or not. if not, strign is not palindrome*/
if(str.charAt(0) != str.charAt(str.length()-1))
{
return false;
}
}
/*if all characters from front anf nack then it is palindrome string.*/
return true;
}
}
Output:
Please Enter a string: abcdcba
abcdcba is a palindrome
Please Enter a string: cat
cat is not a palindrome
Please Enter a string: noon
noon is a palindrome
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.