LoopFun.java 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 * factorial;
  13. } return factorial;
  14. }
  15. /**
  16. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  17. * the first character of each word in upper case.
  18. * For example, given "Ruby on Rails", this method will return "ROR"
  19. * @param phrase
  20. * @return Upper case string of the first letter of each word
  21. */
  22. //get first letter of each word in string
  23. //turn letter into upper case
  24. //returen acronym
  25. public String acronym(String phrase) {
  26. StringBuilder acronym = new StringBuilder();
  27. acronym.append(phrase.charAt(0));
  28. for (int i = 0; i < phrase.length(); i++) {
  29. if(Character.isWhitespace(phrase.charAt(i))) {
  30. acronym.append(phrase.charAt(i + 1));
  31. }
  32. }
  33. return acronym.toString().toUpperCase();
  34. }
  35. /**
  36. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  37. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  38. * at the end of the alphabet, it will wraps around.
  39. * For example:
  40. * 'a' => 'd'
  41. * 'w' => 'z'
  42. * 'x' => 'a'
  43. * 'y' => 'b'
  44. * @param word
  45. * @return the encrypted string by shifting each character by three character
  46. */
  47. public String encrypt(String word) {
  48. String alpha = "abcdefghijklmnopqrstuvwxyz";
  49. StringBuilder encryptedWord = new StringBuilder();
  50. for (int i= 0; i < word.length(); i++) {
  51. char letter = word.charAt(i);
  52. int index = 0;
  53. if (alpha.indexOf(letter + 3) == -1) {
  54. index = ((alpha.indexOf(letter) -26) + 3);
  55. }else {
  56. index = alpha.indexOf(letter + 3);
  57. }
  58. encryptedWord.append(alpha.charAt(index));
  59. }
  60. return encryptedWord.toString();
  61. }
  62. }