1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- public class LoopFun
- {
-
- /**
- * Given a number, return the factorial of that number.
- * For example, given 5, the factorial is 5 x 4 x 3 x 2 x 1 which should return 120.
- * @param number
- * @return the factorial of the number
- */
- public int factorial(int number){
- int factorial = 1;
-
- for (int i = 2; i <= number; i++) {
- factorial *= i;
- }
-
- return factorial;
- }
-
- /**
- * Given a phrase, get the acronym of that phrase. Acronym is the combination of
- * the first character of each word in upper case.
- * For example, given "Ruby on Rails", this method will return "ROR"
- * @param phrase
- * @return Upper case string of the first letter of each word
- */
- public String acronym(String phrase) {
- StringBuilder sbAcronym = new StringBuilder();
-
- String firstCapital = phrase.substring(0, 1).toUpperCase();
- sbAcronym.append(firstCapital);
-
- for (int i = 1; i < phrase.length(); i++) {
- if (phrase.charAt(i) == ' ') {
- sbAcronym.append(phrase.charAt(i + 1));
- }
- }
-
- String Acronym = sbAcronym.toString().toUpperCase();
-
- return Acronym;
- }
-
- /**
- * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
- * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
- * at the end of the alphabet, it will wraps around.
- * For example:
- * 'a' => 'd'
- * 'w' => 'z'
- * 'x' => 'a'
- * 'y' => 'b'
- * @param word
- * @return the encrypted string by shifting each character by three character
- */
- public String encrypt(String word) {
- // char[] toEncode = word.toCharArray();
-
- StringBuilder sbEncryption = new StringBuilder();
-
- char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
-
- for (int i = 0; i < word.length(); i++) {
- for (int j = 0; j < 26; j++) {
- if (word.charAt(i) == arr[j]){
- if (j < 23) {
- sbEncryption.append(arr[(j + 3)]);
- } else {
- continue;
- }
- }
- }
- }
-
- for (int i = 0; i < 26; i++) {
- for (int j = 0; j < word.length(); j++) {
- if (word.charAt(j) == arr[i]){
- if (i >= 23) {
- sbEncryption.append(arr[(i - 23)]);
- } else {
- continue;
- }
- }
- }
- }
-
- String encryption = sbEncryption.toString();
-
- return encryption;
- }
- }
|