LoopFun.java 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 fact = 1;
  11. for(int i = 1; i <= number; i++)
  12. {
  13. fact *= i;
  14. }
  15. return fact;
  16. }
  17. /**
  18. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  19. * the first character of each word in upper case.
  20. * For example, given "Ruby on Rails", this method will return "ROR"
  21. * @param phrase
  22. * @return Upper case string of the first letter of each word
  23. */
  24. public String acronym(String phrase) {
  25. String[] strArr = phrase.split(" ");
  26. String acronym = "";
  27. for(int i = 0; i < strArr.length; i++)
  28. {
  29. String tempStr = strArr[i].substring(0, 1);
  30. acronym = acronym.concat(tempStr.toUpperCase());
  31. }
  32. return acronym;
  33. }
  34. /**
  35. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  36. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  37. * at the end of the alphabet, it will wrap around.
  38. * For example:
  39. * 'a' => 'd'
  40. * 'w' => 'z'
  41. * 'x' => 'a'
  42. * 'y' => 'b'
  43. * @param word
  44. * @return the encrypted string by shifting each character by three character
  45. * ansi 97 ('a') to 122 ('z')
  46. */
  47. public String encrypt(String word) {
  48. char[] charArr = word.toCharArray();
  49. for(int i = 0; i < charArr.length; i++)
  50. {
  51. int tempInt = ((int)charArr[i]) + 3;
  52. if(tempInt > 122)
  53. {
  54. tempInt -= 26;
  55. }
  56. charArr[i] = (char)tempInt;
  57. }
  58. String returnStr = new String(charArr);
  59. return returnStr;
  60. }
  61. }