LoopFun.java 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. public class LoopFun
  2. {
  3. /**
  4. * Given a number, return the factorial of that number.
  5. * For example, given 5, the factorial is 5 x 4 x 3 x 2 x 1 which should return 120.
  6. * @param number
  7. * @return the factorial of the number
  8. */
  9. public int factorial(int n){
  10. int result = 0;
  11. if(n == 0)
  12. {
  13. result = 1;
  14. } else {
  15. return n * factorial(n - 1);
  16. }
  17. return result;
  18. }
  19. /**
  20. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  21. * the first character of each word in upper case.
  22. * For example, given "Ruby on Rails", this method will return "ROR"
  23. * @param phrase
  24. * @return Upper case string of the first letter of each word
  25. */
  26. public String acronym(String phrase) {
  27. //String result = "";
  28. //String newString = "";
  29. //String phra = phrase;
  30. //String[] words = phra.split(" ");
  31. //String word = words[0];
  32. //if(word.length() > 0){
  33. // String[] letters = word.split("");
  34. // result += letters[0].toUpperCase();
  35. // newString = StringUtilities.searchReplaceFirst(phra, words[0], "");
  36. // return result += acronym(newString);
  37. //}else{
  38. // return result;
  39. //}
  40. String result = "";
  41. String[] words = phrase.split(" ");
  42. for(int i = 0; i < words.length; i ++)
  43. {
  44. String word = words[i];
  45. String[] letters = word.split("");
  46. result += letters[0].toUpperCase();
  47. }
  48. return result;
  49. }
  50. /**
  51. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  52. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  53. * at the end of the alphabet, it will wraps around.
  54. * For example:
  55. * 'a' => 'd'
  56. * 'w' => 'z'
  57. * 'x' => 'a'
  58. * 'y' => 'b'
  59. * @param word
  60. * @return the encrypted string by shifting each character by three character
  61. */
  62. public String encrypt(String word) {
  63. char[] chars = word.toCharArray();
  64. String result = "";
  65. for(int i = 0; i < chars.length; i ++)
  66. {
  67. char currentChar = chars[i];
  68. int charValue = (int)(currentChar);
  69. for(int m = 0; m < 3; m ++)
  70. {
  71. charValue ++;
  72. if(charValue > 122)
  73. {
  74. charValue = 97;
  75. }
  76. }
  77. char newChar = (char)(charValue);
  78. String charString = String.valueOf(newChar);
  79. System.out.println(charString);
  80. result += charString;
  81. }
  82. return result;
  83. }
  84. }