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 } }
Showing posts with label Integer. Show all posts
Showing posts with label Integer. Show all posts
Friday, September 25, 2009
Java - Hashtable example - how to create and use
Thursday, September 24, 2009
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; } }
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 } }
Subscribe to:
Posts (Atom)