LoopFun.java 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 sum = 1;
  11. for(int i = 1; i <= number; i++){
  12. sum *= i;
  13. }
  14. return sum;
  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. String[] phraseAcro = phrase.split(" ");
  25. StringBuilder sb = new StringBuilder();
  26. for(int i=0; i < phraseAcro.length; i++){
  27. sb.append(phraseAcro[i].charAt(0));
  28. }
  29. String x = sb.toString().toUpperCase();
  30. return x;
  31. }
  32. /**
  33. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  34. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  35. * at the end of the alphabet, it will wraps around.
  36. * For example:
  37. * 'a' => 'd'
  38. * 'w' => 'z'
  39. * 'x' => 'a'
  40. * 'y' => 'b'
  41. * @param word
  42. * @return the encrypted string by shifting each character by three character
  43. */
  44. public String encrypt(String word) {
  45. String shifted = "";
  46. for (int i = 0; i < word.length(); i++)
  47. {
  48. if (isLetter(word.charAt(i)))
  49. {
  50. shifted = shifted + shift(word.charAt(i), shift);
  51. }
  52. else
  53. {
  54. shifted = shifted + original.charAt(i);
  55. }
  56. }
  57. return shifted;
  58. }
  59. }