123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- 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 n){
- int result = 0;
- if(n == 0)
- {
- result = 1;
- } else {
- return n * factorial(n - 1);
- }
- return result;
- }
-
- /**
- * 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) {
- //String result = "";
- //String newString = "";
- //String phra = phrase;
- //String[] words = phra.split(" ");
- //String word = words[0];
- //if(word.length() > 0){
- // String[] letters = word.split("");
- // result += letters[0].toUpperCase();
- // newString = StringUtilities.searchReplaceFirst(phra, words[0], "");
- // return result += acronym(newString);
- //}else{
- // return result;
- //}
- String result = "";
- String[] words = phrase.split(" ");
-
- for(int i = 0; i < words.length; i ++)
- {
- String word = words[i];
- String[] letters = word.split("");
- result += letters[0].toUpperCase();
- }
- return result;
- }
-
- /**
- * 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[] chars = word.toCharArray();
- String result = "";
- for(int i = 0; i < chars.length; i ++)
- {
- char currentChar = chars[i];
- int charValue = (int)(currentChar);
-
- for(int m = 0; m < 3; m ++)
- {
- charValue ++;
- if(charValue > 122)
- {
- charValue = 97;
- }
- }
-
- char newChar = (char)(charValue);
- String charString = String.valueOf(newChar);
- System.out.println(charString);
- result += charString;
-
- }
-
- return result;
- }
- }
|