12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. {
  13. sum=sum*i;
  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 result = phrase.replaceAll("\\B.|\\P{L}", "").toUpperCase();
  25. return result;
  26. }
  27. /**
  28. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  29. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  30. * at the end of the alphabet, it will wraps around.
  31. * For example:
  32. * 'a' => 'd'
  33. * 'w' => 'z'
  34. * 'x' => 'a'
  35. * 'y' => 'b'
  36. * @param word
  37. * @return the encrypted string by shifting each character by three character
  38. */
  39. public String encrypt(String word) {
  40. String s = "";
  41. int shift = 3;
  42. int len = word.length();
  43. for (int i =0; i <len; i++) {
  44. char c = (char) (word.charAt(i) + shift);
  45. if (c > 'z') {
  46. s += (char) (word.charAt(i) - (26-shift));
  47. } else {
  48. s+= (char) (word.charAt(i) + shift);
  49. }
  50. }
  51. return s;
  52. }
  53. }