Answer to Question #299360 in Java | JSP | JSF for thader

Question #299360

int i,l,p=0,j; char c; String s,w="",r="";

System.out.println("Enter a String");

s = sc.nextLine(); s = s.trim()+" "; l = s.length();

for (i=0;i<l;i++) {

c = s.charAt(i);

if (c != 32) 

w = w + c;

else { p++;

for (j=w.length()-1;j>=0;j--) {

c = w.charAt(j); r = r + c;

} if (w.compareToIgnoreCase(r) == 0 && r.length() > 1) 

System.out.println(w+"\t"+p);

w = ""; r = "";

}

if (i == l-1) {

p++;

for (j=w.length()-1;j>=0;j--) {

c = w.charAt(j);

r = r + c;

}

if (w.compareToIgnoreCase(r) == 0 && r.length() > 1)

System.out.println(w+"\t"+p); }}}}

Q. Above coding will display palindrome words along with its position that is where it is present in the String. Add a statement to above coding so that it will display ''No palindrome words found" if there is not a single palindrome word present in the entered String.


1
Expert's answer
2022-02-18T12:51:03-0500
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i, l, p = 0, j, fu = 0;
        char c;
        String s, w = "", r = "";
        System.out.println("Enter a String");
        s = sc.nextLine();
        s = s.trim() + " ";
        l = s.length();
        for (i = 0; i < l; i++) {
            c = s.charAt(i);
            if (c != 32)
                w = w + c;
            else {
                p++;
                for (j = w.length() - 1; j >= 0; j--) {
                    c = w.charAt(j);
                    r = r + c;
                }
                if (w.compareToIgnoreCase(r) == 0 && r.length() > 1) {
                    System.out.println(w + "\t" + p);
                    fu++;
                }
                w = "";
                r = "";
            }
            if (i == l - 1) {
                p++;
                for (j = w.length() - 1; j >= 0; j--) {
                    c = w.charAt(j);
                    r = r + c;
                }
                if (w.compareToIgnoreCase(r) == 0 && r.length() > 1) {
                    System.out.println(w + "\t" + p);
                    fu++;
                }
            }
        }
        if(fu == 0){
            System.out.println("No palindrome words found");
        }
    }
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS