为什么这不仅会返回字符串,如果它是回文?

时间:2016-03-26 21:17:24

标签: java

下面是我为了让用户输入几个不同的字符串而编写的代码,检查每个字符串是否为回文,并且仅返回回文结构。目前,将返回所有输入的字符串。似乎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();
}
}

3 个答案:

答案 0 :(得分:1)

在调用String之前,您需要使用StringBuilder方法从toString创建equals

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

答案 1 :(得分:1)

宣布

  

StringBuilder语句= new StringBuilder(userInput);

&#34;句子&#34;如果userInput更改,变量将不会更改。您需要在每次需要时重新创建StringBuilder。

这是固定代码:

static void checkPalin() {

    Scanner input = new Scanner(System.in);
    int i = 0;
    String userInput = "";

    System.out.print("Enter the number of strings: ");

    StringBuilder palindrome = new StringBuilder();
    int stringNumber = input.nextInt();

    System.out.println("Enter the strings:");

    while (i <= stringNumber) {
        userInput = input.nextLine();
        String reversed = new StringBuilder(userInput).reverse().toString();
        if (reversed.equals(userInput)) {
            palindrome.insert(0, " " + userInput);
        }

        i++;
    }
    System.out.println("The palindromes are: " + palindrome);
}

答案 2 :(得分:0)

你必须写类似

的内容
new StringBuilder(sentence.toString()).reverse().equals(sentence) 
你的if

中的