gpt4 book ai didi

java - 为什么这不仅会返回回文字符串?

转载 作者:行者123 更新时间:2023-12-02 03:46:38 24 4
gpt4 key购买 nike

下面是我编写的代码,目的是让用户输入几个不同的字符串,检查每个字符串是否是回文,然后仅返回回文。目前,所有输入的字符串都将被返回。看来 IF 语句 if 不能正常工作。关于如何返回正确的字符串有什么建议吗?

import java.util.Scanner;

public class hh {

static void checkPalin () {
// creates a scanner
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";

// asks the user for the number of strings
System.out.print("Enter the number of strings: ");

StringBuilder sentence = new StringBuilder(userInput);

StringBuilder palindrome = new StringBuilder();

// stores the number of strings user will enters
int stringNumber = input.nextInt();

// prompts the user to enter in their sentences
System.out.println("Enter the strings:");

// this loop will go until the number of strings entered are entered
while(i <= stringNumber){

userInput = input.nextLine();
if(sentence.reverse().equals(sentence)){
palindrome.insert(0, " " + userInput);
}
i ++;
}
// if( sentence == sentence.reverse()){
System.out.println("The palindromes are: " + palindrome);
}


public static void main(String[] args) {

checkPalin();
}
}

最佳答案

您需要创建 String来自StringBuilder使用toString调用equals之前的方法:

if(new StringBuilder(userInput).reverse().toString().equals(userInput)) { ... }

关于java - 为什么这不仅会返回回文字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com