LoopFun.java 2.3KB

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 factorial = 1;
  11. for(int i = 1; i <= number; i++) {
  12. factorial *= i;
  13. }
  14. return factorial;
  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. StringBuilder acronym = new StringBuilder();
  25. acronym.append(phrase.charAt(0));
  26. for(int i = 0; i < phrase.length(); i++){
  27. if(Character.isWhitespace(phrase.charAt(i))) {
  28. acronym.append(phrase.charAt(i + 1));
  29. }
  30. }
  31. return acronym.toString().toUpperCase();
  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 alphabet = "abcdefghijklmnopqrstuvwxyz";
  47. StringBuilder encryptedWord = new StringBuilder();
  48. for(int i = 0; i < word.length(); i++) {
  49. char letter = word.charAt(i);
  50. int index = 0;
  51. if(alphabet.indexOf(letter + 3) == -1) {
  52. index = ((alphabet.indexOf(letter) - 26) + 3);
  53. } else {
  54. index = alphabet.indexOf(letter + 3);
  55. }
  56. encryptedWord.append(alphabet.charAt(index));
  57. }
  58. return encryptedWord.toString();
  59. }
  60. }