So, In this lab I am doing I am trying to make a program in java and I need help
ID: 3729857 • Letter: S
Question
So, In this lab I am doing I am trying to make a program in java and I need help
Here are the steps on how to do the lab
1. In this lab you will try to determine whether a string is a palindrome. A palindrome is a string that reads the same backward or forward.
2. Here are the looping steps you will implement:
3. Ask the user to type in a string (contains no white space characters);
4. Read the string from the standard input;
5. Check whether the string is a palindrome;
6. Print out answer onto the screen;
7. If the user enters an empty line then the program exits, otherwise go back to step a and ask the user to type in another string then repeat the steps.
8.You will not create anything in the collection package.
9.You will create a Lab4 class under the lab package.
10.In the Lab4 class you will create a static void test() method and another static method to verify whether the user input string is a palindrome.
11. You are required to implement your palindrome verification method as a recursive method.
12. Your test method should call the palindrome verification method to verify each input string.
13. Under the main package, in the Main class, remove (or comment it out) the contents of the main method we have added in the last lab (or project) and do the following:
Lab4.test();
Compile and test your implementation.
Explanation / Answer
import java.io.*;
import java.util.Scanner;
class Palindrome
{
// A recursive function that checks a str(s..e)
// is palindrome string or not.
static boolean isPalRec(String str, int s, int e)
{
// If there is only one character
if (s == e)
return true;
// If first and last characters do not match
if ((str.charAt(s)) != (str.charAt(e)))
return false;
// If there are more than two characters,
// check if middle substring is also
// palindrome or not.
if (s < e+1)
return isPalRec(str, s+1, e-1);
return true;
}
static boolean isPalindrome(String str)
{
int n = str.length();
// An empty string is considered as
// palindrome
if (n == 0) // no need for this condition since we are giving
//input string of length greater than 0
return true;
return isPalRec(str, 0, n-1);
}
// Main Function
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter string ");
String str = s.nextLine();
while(str.length()==0){
System.out.println("Enter string ");
str = s.nextLine();
}
if (isPalindrome(str))
System.out.println(str+ "is Palindrome string");
else
System.out.println(str+ "is not a Palindrome string");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.