LoopFun.java 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. System.out.print(result);
  34. }
  35. return result;
  36. }
  37. /**
  38. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  39. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  40. * at the end of the alphabet, it will wraps around.
  41. * For example:
  42. * 'a' => 'd'
  43. * 'w' => 'z'
  44. * 'x' => 'a'
  45. * 'y' => 'b'
  46. * @param word
  47. * @return the encrypted string by shifting each character by three character
  48. */
  49. public String encrypt(String word) {
  50. return null;
  51. }
  52. }