2014年12月26日 星期五

java程式設計題目---數字處理【迴文判斷(使用method)】

Write the methods with the following headers:
public static int reverse(int number)
public static Boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome.



  1. import java.util.Scanner;
  2.  
  3. public class C1
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8. Scanner input = new Scanner(System.in);
  9. System.out.println("請輸入整數:");
  10. int number = input.nextInt();
  11. int startnumber = number;
  12. //要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!!
  13. //呼叫 reverse 和 isPalindrom
  14. System.out.println(reverse(number));
  15. number = startnumber;//呼叫使用者最原始輸入的那個值
  16. System.out.println(isPalindrom(number));
  17.  
  18. }
  19.  
  20. public static int reverse(int number)
  21. {
  22. int[] array = new int[10];
  23. int i = 0;
  24. int z = number;
  25. int count = 1;
  26. int t = 1;
  27. int result = 0;
  28. while(number > 0)
  29. {
  30. int a = number % 10;
  31. array[i] = a;
  32. z = number / 10 ;
  33. number = z;
  34. i++ ;
  35. count = count + 1;
  36. }
  37. for(int a = count - 2 ; a >= 0 ; a--)
  38. {
  39. int c = array[a] * t ;
  40. result = result + c;
  41. t = t * 10;
  42. }
  43. return result;
  44. }
  45. //
  46. public static boolean isPalindrom(int number)
  47. {
  48. int inputnumber = number ;
  49. //要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!!
  50. int[] array = new int[10];
  51. int i = 0;
  52. int z = number;
  53. int count = 1;
  54. int t = 1;
  55. int result = 0;
  56. boolean bool = new Boolean(true) ;
  57. while(number > 0)
  58. {
  59. int a = number % 10;
  60. array[i] = a;
  61. z = number / 10 ;
  62. number = z;
  63. i++ ;
  64. count = count + 1;
  65. }
  66. for(int a = count - 2 ; a >= 0 ; a--)
  67. {
  68. int c = array[a] * t ;
  69. result = result + c;
  70. t = t * 10;
  71. }
  72. if( inputnumber == result )
  73. {
  74. bool = true ;
  75. }
  76. else if(inputnumber != result)
  77. {
  78. bool = false ;
  79. }
  80. return bool;
  81. }
  82. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...