Add the following to this working java code: 1. The interface method should veri
ID: 3547245 • Letter: A
Question
Add the following to this working java code:
1. The interface method should verify that the string has at least one character, and display an appropriate error message if necessary.
2. Your main method should use a do-while loop to allow the user to check multiple strings.
import java.util.Scanner;
public class PolyndromTest {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String text = inScanner.nextLine();
if (isPolindrome(text)) {
System.out.println(text + " is polindrome ");
} else {
System.out.println(text + " is not polindrome ");
}
}
private static boolean isPolindrome(String str) {
str = str.toUpperCase();
str = str.replaceAll("[^A-Za-z]", "");
if (str.length() == 0 || str.length() == 1)
return true;// if length =0 OR 1 then it is
else if (str.charAt(0) == str.charAt(str.length() - 1))
return isPolindrome(str.substring(1, str.length() - 1));
return false;
}
}
P.S. I will give rating.
P.S.S. Please ignore my current "Answer rated %." It is false.
Explanation / Answer
package mypro;
import java.util.Scanner;
public class PolyndromTest {
private static boolean isPolindrome(String str) {
str = str.toUpperCase();
str = str.replaceAll("[^A-Za-z]", "");
if (str.length() == 0 || str.length() == 1)
return true;// if length =0 OR 1 then it is
else if (str.charAt(0) == str.charAt(str.length() - 1))
return isPolindrome(str.substring(1, str.length() - 1));
return false;
}
static void checkchar(String str){
int count=0;
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if((ch>=65 && ch <=90) || (ch>=97 && ch <=122)){
count++;
}
}
if(count == str.length()){
System.out.println(" String has atleast one character");
}
else{
System.out.println("Error: String has other charcter also");
}
}
public static void main(String[] args) {
String str="";
do{
Scanner inScanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String text = inScanner.nextLine();
checkchar(text);
if (isPolindrome(text)) {
System.out.println(text + " is polindrome ");
} else {
System.out.println(text + " is not polindrome ");
}
System.out.print("Do you want more yes/no=");
str = inScanner.nextLine();
}while(str.equals("yes"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.