簡體   English   中英

Java Palindrome計划(我正在進行中)?

[英]Java Palindrome Program (am I on track)?

我只有6個月的Java經驗(我也是新來的)所以如果我的代碼中的內容看起來不完整,請耐心等待。 請注意,它仍在進行中。 我正在嘗試編寫一個程序,它接受字符串並只打印那些回文。

, which has a String parameter and - returns a Boolean based on whether the string is a palindrome or not. 我應該: - 創建一個名為的方法,它有一個String參數,並根據字符串是否是回文返回一個布爾值。 to print only the palindromes. 然后 - 修改main方法使用只打印回文。

例如,如果我輸入:“女士詹姆斯蘋果媽媽計時器”,它應該打印“女士”和“媽媽”。

這基本上就是我想寫的程序:例如:讓我們用“女士”這個詞。 ada "). 程序將檢查第一個和最后一個字母是否匹配(“ ada ”)。 d m). And so on and so forth. 如果這是真的,那么它將檢查下一個字母,這次是“a”和“a”(“m d m”)。依此類推。

這是我到目前為止的Java代碼:

public class Palindrome 
{
    private String theWord; //Error: The value of the field Palindrome.theWord is not used

    public boolean isPalindrome( String theWord ) {
        int firstPointer = 0;
        int secondPointer = theWord.length() - 1;

        for ( int i = 0; i < theWord.length( ); i++ ) {
            if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved or is not a field
                return true;
            }
            return false;
        }
    }


    public static void main( String[] theWord ) {
        Palindrome = new Palindrome( ); //Error: Palindrome cannot be resolved to a variable

        for ( int i = 0; i < theWord.length; i++ ) {
            while (firstPointer < secondPointer) { //Error: "firstPointer" cannot be resolved to a variable. "secondPointer" cannot be resolved to a variable
                if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) {  //Error: charAt cannot be resolved to a variable or is not a field. Cannot invoke length() on the array type String[]
                    firstPointer++; //Error: "firstPointer" cannot be resolved to a variable
                    secondPointer++; //Error: "secondPointer" cannot be resolved to a variable
                }
                System.out.println(theWord);
            }
        }
    }
}

知道我哪里出錯了任何幫助都將非常感激。 請不要只給我正確的代碼。 我想弄清楚這一點。 非常感謝你。

**編輯:我現在已將錯誤列為代碼中的注釋。 順便說一句,我正在使用Eclipse。


- > **編輯2:好的伙計們。 我已經閱讀了你的大部分答案,並且到目前為止能夠糾正我的大部分代碼(到目前為止,非常感謝你們)。 我現在仍然遇到問題的唯一部分就是這部分:

if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) ) {
                    leftPointer++;
                    rightPointer--;

and . 我現在得到一個 這是剩下的唯一兩個錯誤,然后我將測試代碼。 我一直試圖解決它們一段時間,但我仍然不完全確定這些錯誤是什么意思。

Eclipse建議我將theWord.charAt(i)更改為theWord.length ,這不是我想要的。 but I don't think that's right either. 這也暗示我從刪除“()”,但我認為這也不對。

看看你的isPalindrome方法:

if ( theWord.charAt(0) == theWord.charAt (theWord.length() - 1) 

在這里,你總是比較第一個字符和最后一個字符。 在每次迭代中,您應該比較一組不同的字符,直到找到一對不匹配或到達單詞中間的字符串。

你應該使用你的循環的i變量:

if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) 

返回值應該完全相反。 如果找到一對不匹配的字符,則返回false 僅當循環結束而不返回false ,才返回true

一種更好的isPalindrome方法

最簡單的方法可能只是遵循定義 :如果你反轉字符串,它仍然是相同的,那么它是一個回文:

public static boolean isPalindrome(String input)
{
    String reverse = new StringBuilder(input).reverse().toString();
    return input.equalsIgnoreCase(reverse);
}

但是如果存在教育目標(?) ,並且由於某種原因應該使用迭代器,那么從字符串的外部向內部迭代更有意義。

public static boolean isPalindrome(String input)
{
  int length = input.length();
  for (int i = 0; i < length/2 ; i++)
  {
    if (input.charAt(i) != (input.charAt(length-1-i))) return false;
  }
  return true;
}

短語解析

在您的示例中,您使用了主String[]參數的輸入。 這里只是一些信息,以防您想手動將其拆分為單詞。

相當於你現在得到的:

String[] words = phrase.split("\\s+");
for (String word : words) 
{
  // do stuff
}

split方法使用分隔符將String拆分為String[] 分隔符\\\\s是一個正則表達式,表示各種空格(不僅是空格,還有制表符,換行符等等)。

但它並不完美(也不是你的方式),短語中仍然可以有逗號 ,圓點和其他標記。 您可以使用Character.isLetterOrDigit方法在迭代中過濾這些字符。 或者,您可以執行replace(...)以刪除逗號,點和其他標記。 或者您也可以使用更復雜的正則表達式。

關於你的代碼

第一條錯誤消息: “未使用該字段的值” 錯誤消息是由全局私有字段theWord引起的,因為它從未被使用過。 它沒有被使用,因為你在方法isPalindrom(String theWord)也有一個具有相同名稱的參數。 每當你在該方法中引用theWord ,它總是會在考慮全局變量之前利用方法參數。

看起來你被困在這里有一個設計矛盾 什么是Palindrome課程? 有兩種選擇:

  1. 它應該是像Math類一樣的工具箱嗎? 比如boolean value = Palindrome.isPalindrome("madam");
  2. 或者它應該是您使用構造函數實例化的對象? 比如boolean value = new Palindrome("madam").isPalindrome();

選項1:工具箱:

public class Palindrome 
{
  // removed the private field theWord

  // make this method static !!
  public static boolean isPalindrome( String theWord ) {
    ...
  }

  public static void main( String[] theWord ) {
    // remove the Palindrome object

    // inside the loop check use the static method 
    // which does not require an object.
    if ( Palindrome.isPalindrome(word))
    {
    }
  }
}

選項2:一個對象

public class Palindrome 
{
  // keep the private field theWord
  private String theWord;

  public Palindrome(String theWord)
  {
    // set the value of the argument to the private field
    this.theWord = theWord;
  }

  // don't make this method static 
  // also you don't need the parameter any more.
  // it will now use the global field theWord instead of a parameter.
  public boolean isPalindrome() {
    ...
  }

public static void main( String[] theWord ) {
    // inside the loop check use an object
    Palindrome palindrome = new Palindrome(word);
    if ( palindrome.isPalindrome())
    {
    }
}

至於firstPointer和secondPointer的錯誤。 您需要定義和初始化這些變量。 int firstPointer = 0; 在循環之前。

好吧,讓我們把所有東西都分解成很小的塊。

  1. 輸入一個字符串
  2. 解析字符串,檢查它是否是回文。
  3. 打印出字符串中的單詞paindromes。

     public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a sentence: "); String sentence = scan.nextLine(); // 1. String[] words = sentence.split(" "); for (String word : words) { // 3. if (isPalindrome(word)) { System.out.println(word); } } } /** * Check if the string is a palindrome. * @param string * @return True if string is palindrome. */ public static boolean isPalindrome(String string) { // 2. for (int i = 0; i < string.length() / 2; i++) { if (string.charAt(i) != string.charAt(string.length() - i - 1)) { return false; } } return true; }} 

一些解釋

方法/函數isPalindrome是靜態的,因為我們從靜態上下文調用它,即主函數。 如果你想非靜態地使用它,你可以將它放在一個類中,並從該類創建一個對象。 其余的應該是可以理解的。 :-)

在循環中以這種方式檢查它:

boolean isPalin = true;
for ( int i = 0; i < theWord.length( )/2; i++ ) { // loop goes till half since no need to check after that
     if ( !(theWord.charAt(i) == theWord.charAt (theWord.length() - 1 - i)) ) { // will check each letter with each end letter
         isPalin = false;
         break;
     }
}
return isPalin;

另外要添加的東西 -

1 - firstPointer secondPointerisPalindrome的局部變量

2 - 當你把theWord稱為全局變量時,似乎需要傳遞它。 您可以在同一個類中使用它。

3 - main(String [] theWord)中的theWord要求你提供輸入作為參數,最好在運行時輸入控制台輸入。

4 - 在main中你應該拆分每個單詞並將其傳遞給isPalindrome。 在您的代碼中,您不會在任何地方調用isPalindrome進行檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM