为什么我的返回语句不打印字符串?

c3frrgcw  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(422)

我试着让用户输入一些文本并打印出文本是否是回文,并且弄清楚了如何在没有多个类的情况下完成它,但是我对如何使用多个给定类有点迷茫(作业需要它)。另外,我是一个高中生在一个介绍班,所以请容忍我。
我的return语句一直给我错误:不兼容的类型:string不能转换为boolean。

import java.util.Scanner;
public class Palindromes
{
    /**
     * This program lets the user input some text and
     * prints out whether or not that text is a palindrome.
     */

    public static void main(String[] args)
    {
       // Create user input and let user know whether their word is a palindrome or not! 
        String text="";
        System.out.println("Type in your text:");
        Scanner input = new Scanner(System.in);
        text = input.nextLine();

    }

    /**
     * This method determines if a String is a palindrome,
     * which means it is the same forwards and backwards.
     * 
     * @param text The text we want to determine if it is a palindrome.
     * @return A boolean of whether or not it was a palindrome.
     */
    public static boolean isPalindrome(String text)
    {
         String newString= "";
         if (newString.equals(text)){
        System.out.println("It's a palindrome!");
    //return true;
    }
    else{
        System.out.println("It's not a palindrome");
    }
    return newString;
    }

    /**
     * This method reverses a String.
     * 
     * @param text The string to reverse.
     * @return The new reversed String.
     */
    public static String reverse(String text)
    {
        String newString="";
       for(int i = text.length() - 1; i >= 0; i--)
        {
            String character = text.substring(i, i+1);
            newString += character;
        }
        System.out.println("The original string reversed = " +newString);
    }

}
czfnxgou

czfnxgou1#

你宣布 isPalindrome 如果返回类型为boolean…则需要将其设置为string以返回字符串。

public static String isPalindrome(String text)
    {
         String newString= "";
         if (newString.equals(text)){
        System.out.println("It's a palindrome!");
    //return true;
    }
    else{
        System.out.println("It's not a palindrome");
    }
    return newString;
    }
56lgkhnf

56lgkhnf2#

你的代码有一些错误。首先,假设方法是通过声明自动调用的。第二,你的代码不会返回你指定的类型。让我们从 reverse . 该方法应该简单地反转输入 text (并返回反向文本)。你可以用很多方法来做。例如,

public static String reverse(String text) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
        sb.insert(0, text.charAt(i));
    }
    return sb.toString();
}

第二,确定 text 是一个回文,你可以比较倒转 text 与原件 text . 比如,

public static boolean isPalindrome(String text) {
    String newString = reverse(text);
    return newString.equals(text);
}

然后你的 main 方法使用 isPalindrome 以确定输入是否为回文。比如,

public static void main(String[] args) {
    System.out.println("Type in your text:");
    Scanner input = new Scanner(System.in);
    String text = input.nextLine();
    if (isPalindrome(text)) {
        System.out.println("It's a palindrome!");
    } else {
        System.out.println("It's not a palindrome");
    }
}

相关问题