LoopFun.java 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 total = 1;
  11. for(int i = number; i > 0; i--){
  12. total = i * total;
  13. }
  14. return total;
  15. }
  16. /**
  17. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  18. * the first character of each word in upper case.
  19. * For example, given "Ruby on Rails", this method will return "ROR"
  20. * @param phrase
  21. * @return Upper case string of the first letter of each word
  22. */
  23. public String acronym(String phrase) {
  24. StringBuilder finalString = new StringBuilder();
  25. //ALWAYS TAKES FIRST LETTER
  26. finalString.append(phrase.charAt(0));
  27. for(int i = 0; i < phrase.length(); i++){
  28. //CHECKS IF THERES A SPACE
  29. if(phrase.charAt(i) == ' ') {
  30. //IF THERE IS IT ADD IT TO OUR STRING
  31. i++;
  32. finalString.append(phrase.charAt(i));
  33. }
  34. }
  35. //TURNS STRINGBUILDER INTO STRING
  36. String answer = "" + finalString;
  37. //MAKES STRING ALL CAPITALS
  38. return answer.toUpperCase();
  39. }
  40. /**
  41. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  42. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  43. * at the end of the alphabet, it will wraps around.
  44. * For example:
  45. * 'a' => 'd'
  46. * 'w' => 'z'
  47. * 'x' => 'a'
  48. * 'y' => 'b'
  49. * @param word
  50. * @return the encrypted string by shifting each character by three character
  51. */
  52. public String encrypt(String word) {
  53. String newString = "";
  54. for(int i = 0; i < word.length(); i++){
  55. char encrypted = word.charAt(i);
  56. int number = (int) encrypted;
  57. if(number <= 119){
  58. char newChar = (char)(number + 3);
  59. newString = newString + newChar;
  60. } else if(number >= 118){
  61. char newChar = (char)(number - 23);
  62. newString = newString + newChar;
  63. }
  64. }
  65. System.out.println((char) 97);
  66. return newString;
  67. }
  68. }