LoopFun.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 number){
  10. int factorial = 1;
  11. for (int i = 2; i <= number; i++) {
  12. factorial *= i;
  13. }
  14. return factorial;
  15. }
  16. /**
  17. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  18. * the first character of each word in upper case.
  19. * For example, given "Ruby on Rails", this method will return "ROR"
  20. * @param phrase
  21. * @return Upper case string of the first letter of each word
  22. */
  23. public String acronym(String phrase) {
  24. StringBuilder sbAcronym = new StringBuilder();
  25. String firstCapital = phrase.substring(0, 1).toUpperCase();
  26. sbAcronym.append(firstCapital);
  27. for (int i = 1; i < phrase.length(); i++) {
  28. if (phrase.charAt(i) == ' ') {
  29. sbAcronym.append(phrase.charAt(i + 1));
  30. }
  31. }
  32. String Acronym = sbAcronym.toString().toUpperCase();
  33. return Acronym;
  34. }
  35. /**
  36. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  37. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  38. * at the end of the alphabet, it will wraps around.
  39. * For example:
  40. * 'a' => 'd'
  41. * 'w' => 'z'
  42. * 'x' => 'a'
  43. * 'y' => 'b'
  44. * @param word
  45. * @return the encrypted string by shifting each character by three character
  46. */
  47. public String encrypt(String word) {
  48. // char[] toEncode = word.toCharArray();
  49. StringBuilder sbEncryption = new StringBuilder();
  50. char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  51. int k;
  52. for (int i = 0; i < 26; i++) {
  53. for (int j = 0; j < word.length(); j++) {
  54. if (word.charAt(j) == arr[i]){
  55. k = i;
  56. if (k < 23) {
  57. sbEncryption.append(arr[(k + 3)]);
  58. }
  59. if (k >= 23) {
  60. sbEncryption.append(arr[(k - 23)]);
  61. }
  62. }
  63. }
  64. }
  65. String encryption = sbEncryption.toString();
  66. return encryption;
  67. }
  68. }