12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 result = 1;
  11. for(int i=1; i<=number; i++){
  12. result = result * i;
  13. System.out.println();
  14. }
  15. return result;
  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. int firstSpaceIndex = phrase.indexOf(" ");
  26. int lastSpaceIndex = phrase.lastIndexOf(" ");
  27. phrase = phrase.toUpperCase();
  28. String result = phrase.substring(0,1);
  29. while (lastSpaceIndex > firstSpaceIndex && firstSpaceIndex != -1) {
  30. result = result + phrase.substring(firstSpaceIndex+1, firstSpaceIndex+2);
  31. phrase = phrase.substring(0,firstSpaceIndex) + phrase.substring(firstSpaceIndex+1);
  32. firstSpaceIndex = phrase.indexOf(" ");
  33. }
  34. return result;
  35. }
  36. /**
  37. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  38. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  39. * at the end of the alphabet, it will wraps around.
  40. * For example:
  41. * 'a' => 'd'
  42. * 'w' => 'z'
  43. * 'x' => 'a'
  44. * 'y' => 'b'
  45. * @param word
  46. * @return the encrypted string by shifting each character by three character
  47. */
  48. public String encrypt(String word) {
  49. String alphabet = "abcdefghijklmnopqrstuvwxyzabcde";
  50. String codedWord = "";
  51. for (int i=0; i<word.length(); i++) {
  52. int alphaIndex = alphabet.indexOf(word.charAt(i));
  53. codedWord += String.valueOf(alphabet.charAt(alphaIndex+3));
  54. }
  55. return codedWord;
  56. }
  57. }