LoopFun.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 = 2; i <= number; i++)
  12. result *= i;
  13. return result;
  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. public String acronym(String phrase) {
  23. String acronym = "";
  24. acronym += phrase.toUpperCase().charAt(0);
  25. for (int i = 1; i <= phrase.length() - 1; i++) {
  26. if (phrase.charAt(i - 1) == ' ' || phrase.charAt(i - 1) == '-') {
  27. acronym += phrase.toUpperCase().charAt(i);
  28. }
  29. }
  30. return acronym;
  31. }
  32. /*
  33. What can you learn from this solution?
  34. A huge amount can be learnt from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
  35. Here are some questions to help you reflect on this solution and learn the most from it.
  36. What compromises have been made?
  37. Are there new concepts here that I could read more about to develop my understanding?
  38. */
  39. /**
  40. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  41. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  42. * at the end of the alphabet, it will wraps around.
  43. * For example:
  44. * 'a' => 'd'
  45. * 'w' => 'z'
  46. * 'x' => 'a'
  47. * 'y' => 'b'
  48. * @param word
  49. * @return the encrypted string by shifting each character by three character
  50. */
  51. public String encrypt(String word) {
  52. char swap = ' ';
  53. char[] arr = word.toCharArray();
  54. swap(arr, 0, word.length + 3);
  55. int i = arr.length + 3 ;
  56. while(i > 1) {
  57. swap(arr, i, i-1);
  58. }
  59. return new swap;
  60. }
  61. }