我目前正在學習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));
}
}
}
}
我要做的第一件事就是爲'int',我會立即將它轉換爲一個字符串並通過'reverseString'運行它,而不是爲'int'設置一組單獨的函數。只是一個想法。 – lurker
謝謝!我馬上就開始了。 – JSCOTT12
方法文檔的方法之外。典型完成與javadoc註釋(以/ **開始) –