Before I describe the class (CIO) you will implement, here is the program you will use to test it.
class Person
{
public Person( String fn, String ln, int a, double s )
{
firstName = fn; lastName = ln; age = a; salary
= s;
}
public String toString( )
{
return CIO.sprintf( "Person: %-30s", lastName
+ ", " + firstName ) +
CIO.sprintf( "%3d ", age ) +
CIO.sprintf( "%15.2f", salary );
}
private String firstName;
private String lastName;
private int age;
private double salary;
}
class TestCIO
{
public static void main( String[] args )
{
Person p1 = new Person( "Bill", "Clinton", 54,
200000.00 );
Person p2 = new Person( "George", "Bush", 51,
1450000.50 );
Person p3 = new Person( "Little", "Kid", 3,
40.00 );
System.out.println( p1 + "\n" + p2 + "\n" +
p3 );
}
}
As you can see, the CIO class will have overloaded functions called sprintf. sprintf takes a control String and a single extra parameter. The parameter is substituted in place of the %...s, %...d, %...f, or %...c sequence, and a String is returned. In the sequence can be specifications of total number of characters (padding will be added), whether the padding goes before or after, and in the case of floating point number, how many places to the right of the decimal point. There are many other options. In the real sprintf, there can be several % sequences, and unlimited number of variables. We will restrict the Java routine to have only one extra variable, and you are not required to do any error checking at all.
Here is the output of the above code:
Person: Clinton, Bill
54 200000.00
Person: Bush, George
51 1450000.50
Person: Kid, Little
3 40.00
You do not need to know anything about C's sprintf except that you will forward the two sprintf parameters to the Java routine to the real sprintf. The real sprintf takes an initial parameter that is an array of characters (make it very large), plus the control string, and then the unlimited (in our case 1) number of variables. After sprintf fills in the character array, your native code should form a jstring and send it back. As an example, the sprintf of the salary, as shown above, above would be
static char buf[ 1024 ];
// hope this is enough characters
sprintf( buf, "%15.2f", salary );
// call C's sprintf; send buf back
Here is the class declaration for CIO:
class CIO
{
public native static String sprintf( String control, String
var );
public native static String sprintf( String control, int
var );
public native static String sprintf( String control, double
var );
public native static String sprintf( String control, char
var );
}
Submit your source code and sample output.