2013-05-28 123 views
0

我目前正在學習Java,並且剛寫完我的第一個程序。該程序實現了整數和字符串的迴文。我的編碼背景是用C++編寫的,但我想知道是否有人對我如何更好地構建代碼(使其更易於閱讀)有任何建議,或者提示我如何更好地壓縮代碼。請儘可能給予儘可能多的建設性批評。到夏天結束時,我計劃申請入門級軟件工程職位,所以我歡迎任何和所有的反饋意見!多謝你們。如何優化我的迴文代碼?

package projectprac; 

import java.util.Scanner; 

public class ProjectPrac { 

    static Scanner userInput = new Scanner(System.in); 

    public static int reverseInt(int x){ 
     /* This function will reverse an integer value */ 
     int reverse = 0; 
     int temp = x; 
     while(x != 0){ 
      reverse = reverse * 10; 
      reverse = reverse + x % 10; 
      x = x/10; 
     } 
     intPalindromeCheck(temp, reverse); 
     return reverse; 
    } 

    public static String reverseString(String word){ 
     /* This function will return a String value */ 
     String reverse = new StringBuffer(word).reverse().toString(); 
     stringPalindromeCheck(word, reverse); 
     return reverse; 
    } 

    public static void intPalindromeCheck(int one, int two){ 
     /* This function will check to see if int 
     * is a Palindrome 
     */ 
     if(one == two){ 
      System.out.println(one + " is a Palindrome!"); 
     } 
     else{ 
      System.out.println(one + " is NOT a Palindrome!"); 
     } 
    } 

    public static void stringPalindromeCheck(String one, String two){ 
     /* This function will check to see if String is a 
     * Palindrome 
     */ 

     if(one.equals(two)){ 
      System.out.println(one + " is a Palindrome!"); 
     } 

     else{ 
      System.out.println(one + " is NOT a Palindrome!"); 
     } 
    } 

    public static void main(String[] args) { 
     String word; 
     int x = 0; 

     while (x != -1){ 

      System.out.print("What would you like to do 1. reverse int 2. reverse String: "); 
      x = userInput.nextInt(); 

      if(x == 1){ 
       System.out.print("Please input a number: "); 
       x = userInput.nextInt(); 
       System.out.println(reverseInt(x)); 
      } 

      else if (x == 2){ 
       userInput.nextLine(); //skips the new line 
       System.out.print("Please enter a string: "); 
       word = userInput.nextLine(); 
       System.out.println(reverseString(word)); 
      } 
     } 
    } 
} 
+0

我要做的第一件事就是爲'int',我會立即將它轉換爲一個字符串並通過'reverseString'運行它,而不是爲'int'設置一組單獨的函數。只是一個想法。 – lurker

+0

謝謝!我馬上就開始了。 – JSCOTT12

+0

方法文檔的方法之外。典型完成與javadoc註釋(以/ **開始) –

回答

1

你的代碼是很清晰,但會打擊大多數Java程序員奇怪方面:

  • 您使用的static方法
  • ,你是不是封裝你的領域或地方的事實方法。

這些都是小細節,雖然,當然,對於這種規模的玩具程序。

你利用現有的功能來扭轉一個字符串是OK和輸入,這是你能得到這個問題的最佳的大小線性擴展。

另一方面,通過簡單地比較第一個和最後一個字符,然後第二個和最後一個等等,直到找到差異或已經達到中間值,對於字符串迴文測試的恆定加速當然是可能的。這個想法本身並不依賴於編程語言。

0

你的代碼看起來有明確命名的變量和方法還不錯。我同意mbratch,但將int轉換爲字符串。原因有二:

  • 迴文不鍵入特定的,所以服用一個int作爲一個字符串,並扭轉將有相同的結果把它作爲一個int,扭轉它,所以你可以很容易地保持它的字符串和重用您的stringPalindromeCheck()方法。
  • 一旦你要求用戶輸入整數,那麼你會需要一些錯誤處理代碼。如果你要求一個int,並且它們給你「不是int」或「123.4」,那麼你必須檢查它是否有效,如果不是,請再次詢問它們。你永遠不能相信用戶會做他們應該做的事。

消除int相關的輸入提示及其方法將使您易於閱讀的代碼更加清晰。