Monday, July 11, 2011

Java String to number conversion

This entry is from http://www.devdaily.com/java/edu/qanda/pjqa00008.shtml

Two ways to convert number to String
Method 1: using String.valueOf()
String s = String.valueOf(i);
String s = String.valueOf(f); // float
String s = String.valueOf(d); // double
String s = String.valueOf(l); // long

Method 2: using toString() method of the numeric classes
String s = new Integer(i).toString(); // or Integer.toString(i)
String s = new Float(f).toString();
String s = new Double(d).toString();
String s = new Long(l).toString();

Convert String to number:
int anInt = Integer.parseInt("17");
double aDouble = Double.parseDouble("17");

NOTE: The methods above are not exhaustive. Googling will surely yield a few more ways to do conversion.

Accessing instance variable in Python

To access a Python instance variable outside the class:

class Sample:
def __init__(self, max):
self. max = max
....

sampleinstance = Sample(2)
max = sampleinstance.max

Wednesday, July 6, 2011

Java String <-> int conversion

To convert String to int:

Integer.parseInt("17");

To convert int to String:

Integer.toString(17);

Swing JComboBox usage - Getting the text of the selected item

Here is an example of a function handling an ActionPerformed event on a Combo Box.

private void onCategoryChanged(ActionEvent ae){

JComboBox cbCategory = (JComboBox)ae.getSource();
System.out.println(cbCategory.getSelectedIndex()); // Display the item index, 1st item index is 0
System.out.println((String)cbCategory.getSelectedItem()); // Display the string of the selected item

}