LoopFun.java 2.3KB

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