LoopFun.java 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 i = number;
  11. int factorial = 5;
  12. while (i > 1) {
  13. i--;
  14. factorial = i * factorial;
  15. };
  16. return factorial;
  17. }
  18. /**
  19. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  20. * the first character of each word in upper case.
  21. * For example, given "Ruby on Rails", this method will return "ROR"
  22. * @param phrase
  23. * @return Upper case string of the first letter of each word
  24. */
  25. public String acronym(String phrase) {
  26. int i = 0;
  27. String[] splitem = phrase.split("\\s+");
  28. int length = splitem.length - 1;
  29. String acronym = "";
  30. while (i < length) {
  31. acronym += "" + splitem[i].toUpperCase();
  32. }
  33. return acronym;
  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 decode = "";
  49. char convert;
  50. char[] wurd = word.toCharArray();
  51. for (int i = 0; i < word.length(); i++) {
  52. while (Character.isLetter(wurd[i])) {
  53. convert = (wurd[i] + 3 - (int)'a') % 26 + (int)'a';
  54. decode += "" + convert;
  55. }}
  56. String decoded = String.valueOf(convert);
  57. return decoded;
  58. }
  59. }