Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Tuesday, October 6, 2009

Java - pig latin generator

 
package javasomethingsomething;
 
public class Main {
    public static void main(String[] args) {
        // all the heavy lifting is done in the PigLatin class 
        PigLatin pg = new PigLatin();
        String pigSentence = "";
        String sentence = "This is going to be a pig latin sentence";
        // iterate over the sentence with for-each and split by " " 
        for (String s:sentence.split(" ")) {
            pigSentence += pg.getPigLatinForWord(s) + " ";
        }
        // added the trim to remove the trailing space 
        System.out.println(pigSentence.trim());
    }
 
}
 
class PigLatin{
 
    public String getPigLatinForWord(String word) {
        int firstVowel = word.length();
        // yes, I included y as a vowel!! 
        String[] vowels = {"a", "e", "i", "o", "u", "y"};
        for(String s:vowels){
            // if indexOf() finds no match it returns -1 
            if ((word.indexOf(s) < firstVowel) && (word.indexOf(s) != -1)) {
                firstVowel = word.indexOf(s);
            }
        }
        return  word.substring(firstVowel, word.length()) +
                word.substring(0, firstVowel) +
                "ay";
    }
}
 

Thursday, September 24, 2009

Java - find the working directory


import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        // to find out where your application is running 
        //  (sounds easy but its sometimes tricky) 
        System.out.println("This Java applications working directory is:");
        // Java has a list of Properties that it uses for everything 
        // the working directory property is user.dir 
        // you can check it out with: 
        System.out.println(System.getProperty("user.dir"));
 
        // you can see all the properties with this: 
        System.out.println(System.getProperties());
        // it will just dump them all out in a not 
        //  organized way 
 
        // you can also iterate through all of the properties 
        //  and print them out line by linewith: 
        Properties myProps = System.getProperties();
        for (Enumeration e = myProps.keys(); e.hasMoreElements();/**/){
            String key = (String)e.nextElement();
            String value = myProps.getProperty(key);
            System.out.println(key + " = " + value);
        }
    }
}
 
 

Wednesday, September 23, 2009

Java - cast int to string and string to int


public class Main {

    public static void main(String[] args) {
        String s = "23";
        int i = 22;

        // int to string
        String iString = Integer.toString(i);
        System.out.println(iString);
        // output:
        //  22

        // string to int
        int sInt = Integer.parseInt(s);
        System.out.println(sInt);
        // output:
        //  23
    }
}