LoopFun.java 1.8KB

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