Friday, September 25, 2009

Java - a ping example with java's InetAddress.isReachable()

import java.net.*;
public class Main {
 
    public static void main(String[] args) {
        try{
            // a note: 
            // This the isReachable method is problematic 
            // If you are in a coorporate environment 
            // then you are probably (unknown to you) 
            // using proxy servers.  Java needs to know 
            // what the proxy server and port is 
            // DhttpProxy.host=yourproxyhost.com -DhttpProxy.port 
            // 
            // All of testing I've done at home works fine. 
            // You need to configure java to utilize your proxy 
 
            // gather the ip address associated with the host 
            InetAddress[] addresses = InetAddress.getAllByName("yahoo.com");
 
            // iterate through the ip address with for-each 
            for (InetAddress addr:addresses) {
 
                // the timeout is in milliseconds 2 seconds here 
                if (addr.isReachable(2000)){
                    System.out.printf("%s is reachable", addr);
                    System.out.println();
                }
                else{
                    System.out.printf("%s is not reachable", addr);
                    System.out.println();
                }
            }
        }
        catch(Exception e) {
            System.out.println("host is unknown (or unresolvable)");
        }
    }
}
/* 
 *      Output (for me): 
        yahoo.com/69.147.114.224 is reachable 
        yahoo.com/209.131.36.159 is reachable 
        yahoo.com/209.191.93.53 is reachable 
*/ 
 

Java - reverse the word order of a sentence

public class Main {
 
    public static void main(String[] args) {
        Words w = new Words();
        String sentence = "The example sentence is here";
        System.out.println(sentence);
        System.out.println("reversed to:");
        System.out.println(w.reverseWordOrderOfSentence(sentence));
    }
}
 
class Words{
    public String reverseWordOrderOfSentence(String sentence){
        // split up by words 
        String[] words = sentence.split(" ");
        sentence = "";
 
        // iterate backward through the array 
        // rebuilding the sentence from the back forward 
        for (int i=words.length; i>0; i--){
            sentence += words[i-1];
            sentence += " ";
        }
        // remove the trailing white space 
        return sentence.trim();
    }
}
 
/* 
 *      OUTPUT: 
        The example sentence is here 
        reversed to: 
        here is sentence example The 
*/ 
 

Java - extracting rgb values from an image

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
 
public class Main {
    public static void main(String[] args) {
        BufferedImage bimg = null;
        String input = "test.jpg";
        try{
            bimg = ImageIO.read(new File(input));
        }
        catch (Exception e) {
            // the test.jpg must be in the working dir  
            System.out.println(input + " is not in working dir");
        }
 
        System.out.println("height: " + Integer.toString(bimg.getHeight()));
        System.out.println("width: " + Integer.toString(bimg.getWidth()));
 
        // collect the rgb information 
        // regarding a single pixel 
        int rgb = bimg.getRGB(10, 10);
 
        // for some smart reason (that is beyond me) 
        // getting the rgb gives you a single int 
        // 
        // each component of colr occupies 8 bits 
        // this extracts the actual alpha, red, green, blue 
        int a = (rgb >>> 24) & 0xFF;
        int r = (rgb >>> 16) & 0xFF;
        int g = (rgb >>> 8) & 0xFF;
        int b = (rgb >>> 0) & 0xFF;
 
        // here is the proof 
        System.out.println("a: " + Integer.toString(a));
        System.out.println("r: " + Integer.toString(r));
        System.out.println("g: " + Integer.toString(g));
        System.out.println("b: " + Integer.toString(b));
 
        // this scripts output: 
        /* 
            height: 564 
            width: 634 
            a: 255 
            r: 222 
            g: 128 
            b: 184 
        */ 
    }
 
}
 
 

Java - remove vowels from a sentence String

public class Main {

    public static void main(String[] args) {
      NotStatic g = new NotStatic();
      String sentence = "This is my example sentence.";
      String s = g.RemoveVowelsFromSentence(sentence);
      System.out.println(s);

      // output:

      //    Ths s m xmpl sntnc.

    }
}
class NotStatic {

    public String RemoveVowelsFromSentence(String sentence) {
        String[] vowels = {"a", "e", "i", "o", "u", "y"};
        // iterate through the vowel array with for-each

        for (String s:vowels){
            sentence = sentence.replaceAll(s, "");
        }

        return sentence;

    }

}


Java - Hashtable example - how to create and use

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // a hashtable is like a dictionary

        // to put items into the hashtable you 
        // need a key and a value.  The keys must
        // be unique -- while the values can be
        // anything you like
        Hashtable ht = new Hashtable();

        // put new values into ht

        ht.put("name", "Steve");
        ht.put("warpFactor", 9);

        String s = "";
        // looping add
        for (int i=0; i<20; i++) {
            s = Integer.toString(i);
            s += " is a good number";
            ht.put(i, s);
        }

        // use the values in the hashtable

        System.out.println("I hear that " +
                ht.get("name").toString() +
                " has a Warp Factor of " +
                ht.get("warpFactor").toString());

        // outputs:
        // I hear that Steve has a Warp Factor of 9

    }
}


Java - how to create and use a LinkedList

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        LinkedList ll = new LinkedList();

        // add to linked list

        ll.add("first String object");

        // total items in the linked list
        System.out.println(ll.size());
        // indicates:  1

        // the list is not type specific
        // Strings and ints can coexist

        ll.add(22);

        // add ten more items
        for (int i=0; i<10; i++){
            ll.add(i);
        }

        String oType = "";
        // iterate through all existing items
        //  with for-each

        for(Object o:ll){
            oType = o.getClass().toString();
            System.out.println(o.toString() + 
                    ", is type: " + oType);
        }

        // remove items from list
        ll.removeFirstOccurrence(3);

        // remove the first item from the list
        ll.remove();

        // remove the last item from the list
        ll.removeLast();
    }
}



Thursday, September 24, 2009

Java - how to create and use a Vector

import java.util.*;
public class Main {
 
    public static void main(String[] args) {
        Vector v = new Vector();
        // The Vector class is almost identical to the 
        //  ArrayList class.  The main difference is that 
        //  a Vector is thread safe. 
        v.add("number one is a String");
        v.add(22); // number two is an Integer 
 
        for (int i=0; i<10; i++){
            // add ten integers 
            v.add(i);
        }
 
        // iterate through the vector with a foreach 
        for (Object o:v){
            System.out.println(o);
        }
        // as with ArrayLists you'll notice that 
        //  Vectors are not type specific.  You can 
        //  put in whatever you want 
    }
}
 
 

Java - how to create and use an ArrayList

import java.util.*;
 
// related posts:
// old (but fast) school array
// Thread safe vectors
// 
// 


public class Main {
 
    public static void main(String[] args) {
 
        // arraylists do not require a size definition 
        // when you declare or instantiate. 
        // you can add to your hearts content 
        ArrayList al = new ArrayList();
 
        al.add("number one");
 
        // display the size of the ArrayList 
        System.out.println(al.size());
        // indicates:  1 
 
        // fill up with 10 
        for (int i=0; i<10; i++){
            // you'll notice that it just appends to 
            // the existing list.  "number one" remains 
            // and all the numbers are tacked on after 
            al.add(i);
        }
 
        // display all ten with foreach 
        //for (Object o:al 
        for (int i=0; i<al.size(); i++){
            System.out.println(al.get(i) + " is type " +
                    al.get(i).getClass().toString());
        }
 
        // you'll notice from the output that a Java ArrayList 
        // can have a mixture of object types.  Here we 
        // blend Integer and String 
    }
}
 
 

Java - create and use a String or int array

 
public class Main {
    public static void main(String[] args) {
        // standard, fast, old school array 
        // string array 
        String[] stringArray = new String[10];
        stringArray[0] = "first item in array";
        System.out.println("array length: " + stringArray.length);
        // indicates:  10 
        // even if you've only populated 
        // one of the you allocated room for 10 
 
        // you can also for loop through and populate 
        String tempString = "";
        for (int i=0; i<stringArray.length; i++){
            tempString = Integer.toString(i+1);
            stringArray[i] = "arrayitem " + tempString;
        }
 
        // display contents of array 
        //  with a for each 
        for (String s:stringArray){
            System.out.println(s);
        }
 
 
        // same methodology for an int array 
        int[] intArray = new int[10];
        intArray[0] = 213;
    }
 
}
 
 

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);
        }
    }
}
 
 

Java - open and read text file



/* 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
 
package readfile;
 
import java.io.*;
 
 
public class Main {
 
    public static void main(String[] args) {
 
        // this assumes you have 'test.txt' in your working directory 
        String filename = "test.txt";
 
        try {
            // open file 
 
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
 
            // iterate through file's lines 
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
 
 
        }
 
        catch(Exception e) {
            System.out.println("file not found");
            System.out.println(e.getMessage());
            System.out.println(e.toString());
 
        }
 
 
    }
 
}
 
 
// output (for my test file): 
//  one 
//  two 
//  three 
 
 

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
    }
}