在Java上玩这个Palindrome很难

时间:2017-05-11 15:21:23

标签: java

我很难学习java,我希望得到一些帮助。我试图让用户输入一个单词并让系统检查它是否是一个回文。我从其他人那里得到了一些代码以获得一些帮助,但我已经陷入困境。

import java.util.Scanner;

class PalidromeTester
{

    public static boolean isPalindrome (String[] word) {
       for (int i=0; i< word.length; i++) { 
            if (!word[i].equals( word[word.length-1-i])){
                return false; 
            }
        }
        return true; 

    // read word
    public static String readWord(Scanner input){
      String word = input.nextLine();
      word = word.toLowerCase();
      return word;
    }

    // display results to the screen
    public static void displayResults(boolean result){
      // display the results
      String msg = "\nThat string ";
      msg += (result == true) ? " IS " : " is NOT ";
      msg += " a palindrome.\n";
      System.out.println(msg);
    }

    // main function
    public static void main(String[] args){
      // input scanner
      System.out.print('\u000C');
      System.out.println("Enter the word: ");
      Scanner input = new Scanner(System.in);
      PalidromeTester.readWord(input);
    }
}

1 个答案:

答案 0 :(得分:2)

假设您需要,我认为这就是您的需要。我已经评论了代码本身所做的更改,以便向您指出为什么首先要进行更改。还记得有多种方法可以解决问题,这只是其中一种可能性。随意创新,并添加自己的技术来解决这个问题。

import java.util.Scanner;

public class Palindrome { //<-- added public to the class otherwise main method won't be called

public static boolean isPalindrome(String word) { //<--changed the String[] to String
    for (int i = 0; i < word.length(); i++) {
        if (!(word.charAt(i) == word.charAt(word.length() - 1 - i))) { //Since [] will not work on Strings, using charAt() to do the same thing
            return false;
        }
    }
    return true;
}

// read word
public static String readWord(Scanner input) {
    String word = input.nextLine();
    word = word.toLowerCase();
    return word;
}

// display results to the screen
public static void displayResults(boolean result) {
    // display the results
    String msg = "\nThat string ";
    msg += (result == true) ? " IS " : " is NOT ";
    msg += " a palindrome.\n";
    System.out.println(msg);
}

// main function
public static void main(String[] args) {
    // input scanner
    System.out.print('\u000C');
    System.out.println("Enter the word: ");
    String s = readWord(new Scanner(System.in)); //Added a call to the readWord method and also passed a Scanner reference to the method and 
                                                 //storing the read word in String s
    boolean result = isPalindrome(s); //Added a call to the palindrome method and also passing the read string s to the method to find whether
                                      //it is palindrome or not and storing the method return value in boolean result variable
    displayResults(result); //Finally calling the displayResults with the result we got from isPalindrome() to display the appropriate message
}
}