[英]The Palindrome words are not being properly displayed
package school;
import java.util.*;
public class PalindromeWords {
boolean palindrome(String S) {
String check="";
for(int i = S.length()-1;i>=0;i--) {
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)) {
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++) {
if(S.charAt(i)==' ') {
word = S.substring(flag,i);
if(ob.palindrome(word)) {
System.out.println(word);
flag =i+1;
}
}
}
}
}
我被分配了一個作業,其中我必須編寫一個Java程序來打印句子中的所有回文詞。 這是我編寫的代碼,但沒有得到正確的輸出。
如您所見,控制台中的輸出未顯示任何查詢結果。
您應該在if statement
外移動增加標志的步驟。 否則,它僅在第一個單詞是回文詞時才起作用。
if(ob.palindrome(word)) {
System.out.println(word);
}
flag = i+1;
在循環外使用該標志。
if(ob.palindrome(word)==true) {
System.out.println(word);
}
flag =i+1;
此代碼應該起作用。
這是另一個解決方案,如下所示:
碼:
import java.util.*;
public class PalindromeWords
{
boolean isPalindrome(String S)
{
boolean result = false;
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S))
{
result = true;
}
return result;
}
public static void main(String args[])
{
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String str = sc.nextLine();
String[] words = str.split(" ");
for(int i=0; i < words.length; i++)
{
if(ob.isPalindrome(words[i]))
{
System.out.println(words[i]);
}
}
}
}
輸出:
Enter the sentence.
hello mAdam
mAdam
boolean palindrome(String S){
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)==true)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
Para ob = new Para();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++)
{
if(S.charAt(i)==' ')
{
word = S.substring(flag,i);
if(ob.palindrome(word)==true)
{
System.out.println(word);
}flag =i+1;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.