Чтобы проверить каждое слово в предложении, являются ли они палиндромом или нет - PullRequest
0 голосов
/ 21 сентября 2019

В заданных предложениях поменяйте местами каждое слово и напечатайте обратные слова в предложениях.если есть палиндром, напечатайте эти слова. если нет палиндрома, напечатайте «Нет палиндрома».это то, что я написал

import java.util.Scanner;   
public class main{   
    public static void main(String[] args){     
        Scanner input=new Scanner(System.in);  
        String s1=input.nextLine();   
        String arr[]=s1.split("\\s",s1.length());   
        int count=0;    
        String palindrome[]=new String[s1.length()];    

        for(int i=0;i<arr.length;i++){



             String s2="";
          for(int j=arr[i].length()-1;j>=0;j--){
          s2=s2.concat(Character.toString(arr[i].charAt(j)));
          System.out.println(arr[i].charAt(j));
          }
          System.out.print(" ");
          if(arr[i].equals(s2)){
              count++;
              palindrome[i]=s2;
          }

        }

        if(count>0){
             for(String i:palindrome)
             System.out.println(i);}
             else 
             System.out.println("Not a palindrome");
        }

    }

Но код не дает правильного вывода.

Ответы [ 3 ]

2 голосов
/ 21 сентября 2019

Это должно работать:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String s1 = input.nextLine();
    String[] arr = s1.split(" ");
    StringBuilder output = new StringBuilder();
    for (String currentWord : arr) {
        String reverseWord = new StringBuilder(currentWord).reverse().toString();
        if (currentWord.equals(reverseWord)) {
            output.append(reverseWord);
        } else {
            output.append("No Palindrome ");
        }
    }
    System.out.println(output);
}
1 голос
/ 21 сентября 2019

Вот рабочий code, который вы можете использовать для проверки input string/number, равного palindrome или not palindrome

код:

    import java.util.*;
    class stackOverflow {

        public static void main(String[] args) {
            String original, reverse = ""; // Objects of String class  
            Scanner in = new Scanner(System.in);   
            System.out.println("Enter a string/number to check if it is a palindrome or not:");  
            // takes input string
            original = in.nextLine();   
            int length = original.length();   // length of the string to do iteration on it
            // check the string from the end to the start to reverse it
            // read and append it with the reverse variable in backward
            for ( int i = length - 1; i >= 0; i-- )  
               reverse = reverse + original.charAt(i);

            // Finally we check if the input string and reversed string
            if (original.equals(reverse))  
               System.out.println("Is palindrome.");  
            else  
               System.out.println("Not palindrome.");   
         }
    }

I've edited your code and now it's working fine:

  import java.util.*;
    class stackOverflow {
        public static void main(String[] args){     
            Scanner input=new Scanner(System.in);  
            String s1=input.nextLine();   
            String arr[]=s1.split("\\s",s1.length());   

            for(int i=0;i<arr.length;i++){

              String s2="";
              for(int j=arr[i].length()-1;j>=0;j--){
              s2=s2.concat(Character.toString(arr[i].charAt(j)));
              //System.out.println(arr[i].charAt(j));
              }
              //System.out.print(" ");
              if(arr[i].equals(s2)){
                  //palindrome[i]=s2; // you are inserting the s2 value into the first element of the array, 
                  //so the rest of the positions remains empty/null that's not a problem to solve palindrome

                System.out.println("Is a palindrome");
              }
              else 
                 System.out.println("Not a palindrome");
            }

        }
    }

Надеюсь, это поможет, счастливое кодирование

0 голосов
/ 21 сентября 2019

Вот более короткий способ сделать это:

//prints each palindome word in a sentence
Arrays.asList(sentence.split(" ")).stream().filter(this::isPalindrome).forEach(System.out::println);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...