LoopFun.java 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package QuizWeek1;
  2. public class LoopFun
  3. {
  4. /**
  5. * Given a number, return the factorial of that number.
  6. * For example, given 5, the factorial is 5 x 4 x 3 x 2 x 1 which should return 120.
  7. * @param number
  8. * @return the factorial of the number
  9. */
  10. public int factorial(int number){
  11. int result = 1;
  12. if (number == 0){
  13. result = 1;
  14. } else {
  15. for (int i = 1; i <= number; i++){
  16. result *= i;
  17. }
  18. }
  19. return result;
  20. }
  21. /**
  22. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  23. * the first character of each word in upper case.
  24. * For example, given "Ruby on Rails", this method will return "ROR"
  25. * @param phrase
  26. * @return Upper case string of the first letter of each word
  27. */
  28. public String acronym(String phrase) {
  29. String newPhrase = phrase.toUpperCase();
  30. char[] charArray = newPhrase.toCharArray();
  31. String firstLet = Character.toString(charArray[0]);
  32. //System.out.println(firstLet);
  33. for (int i = 1; i < charArray.length; i++){
  34. if (charArray[i] == ' '){
  35. System.out.println(charArray[i]);
  36. firstLet += (charArray[i]+1);
  37. System.out.println(firstLet);
  38. }
  39. }
  40. return firstLet;
  41. }
  42. /**
  43. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  44. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  45. * at the end of the alphabet, it will wraps around.
  46. * For example:
  47. * 'a' => 'd'
  48. * 'w' => 'z'
  49. * 'x' => 'a'
  50. * 'y' => 'b'
  51. * @param word
  52. * @return the encrypted string by shifting each character by three character
  53. */
  54. public String encrypt(String word) {
  55. // ASCII Table - a = 97, z = 122
  56. char[] charArray = word.toCharArray();
  57. for (int i = 0; i < charArray.length; i++){
  58. (int)charArray[i] += 3;
  59. if ((int)charArray[i] > 119){
  60. (int)charArray[i] -= 23;
  61. }
  62. }
  63. return null;
  64. }
  65. }