Recent Changes - Search:

Main.SideBar (edit)



Java

Round to n significant figures

I needed to round numbers to a given number of significant figures, irrespective of their size, here is an example of what I cam up with:

public static void main(String[] args) {
        double vals[] = {123456.00, 1.23456, 0.00123456 };

        double sigFigs = 3;
        double base10 = Math.log(10);//factor to convert to natural log to base 10

        for(double v : vals) {

                //get the number of digits in the value
                int nDigits =  1 + (int) (Math.round(Math.log(v)/base10));

                //create a scaling factor
                double factor = Math.pow(10,nDigits) /  Math.pow(10,sigFigs);
                //divide by the factor, round and multiply to reduce the significant figures
                double vSigFigs = Math.round( v/factor) * factor;

                /* the double above is pretty close but being a double means that it may not be exact
                * convert to a BigDecimal of the correct scale */
                BigDecimal bd = new BigDecimal(vSigFigs);
                // the scale is the number of digits after the decimal point
                int scale = 1 + Math.abs( (int)Math.round( (Math.log(factor)/base10) ) );
                bd = bd.setScale( scale , BigDecimal.ROUND_HALF_UP);
                System.out.println("Value=" + v + "  rounded=" + bd.toPlainString());


        }
}

List database tables/columns

Here is a way of listing the tables and columns in a database via JDBC


import java.sql.*;

public class ReadDb {


        public static void main(String[] args) {

                //open the db
                try {
                        // Load the JDBC driver
                        String driverName = "oracle.jdbc.driver.OracleDriver";
                        Class.forName(driverName);

                        // Create a connection to the database
                        String serverName = "localhost";
                        String portNumber = "1521";
                        String sid = "db";
                        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
                        String username = "user";
                        String password = "password";
                        Connection cnn = DriverManager.getConnection(url, username, password);

                        String catalog = null;
                        String schema  = null;
                        for (int i=0; i<args.length; i=i+2) {
                                {
                                        if (args[i].equals("-cat")) {
                                                catalog = args[i+1];
                                        }
                                        else if (args[i].equals("-scm")) {
                                                schema = args[i+1];
                                        }
                                }
                        }

                        listTables(cnn, catalog, schema);

                        cnn.close();

                }
                catch (ClassNotFoundException e) {
                        // Could not find the database driver
                        e.printStackTrace();
                }
                catch (SQLException e) {
                        // Could not connect to the database
                        e.printStackTrace();
                }
                catch (ArrayIndexOutOfBoundsException e) {
                        System.out.println("Error in argument list");
                }
        }

        public static void listTables(Connection cnn, String catalog, String schema) {
                try {
                        // Gets the database metadata
                        DatabaseMetaData dbmd = cnn.getMetaData();

                        // Specify the type of object; in this case we want tables
                        String[] types = {"TABLE"};
                        ResultSet resultSet = dbmd.getTables(null, null, "%", types);

                        // Get the table names
                        while (resultSet.next()) {

                                // Get the table name
                                String tableName = resultSet.getString(3);

                                // Get the table's catalog and schema names (if any)
                                String tableCatalog = resultSet.getString(1);
                                String tableSchema = resultSet.getString(2);

                                //should we list this catalog/schema?
                                boolean listCat = true;
                                if (catalog != null && !catalog.equals(tableCatalog)) listCat=false;
                                boolean listScm = true;
                                if (schema != null && !schema.equals(tableSchema)) listScm=false;

                                if (listCat && listScm) {
                                        try {
                                                System.out.println('\n' + tableName + "\t" + tableCatalog + "\t" + tableSchema);
                                                //list columns - seems that we need to do a select * from table and
                                                //then get columns from result set
                                                String sql = "SELECT * from " + tableName;

                                                // Create a result set
                                                Statement stmt = cnn.createStatement();
                                                ResultSet rs = stmt.executeQuery(sql);

                                                // Get result set meta data
                                                ResultSetMetaData rsmd = rs.getMetaData();
                                                int numColumns = rsmd.getColumnCount();

                                                // Get the column names; column indices start from 1
                                                for (int i=1; i<numColumns+1; i++) {
                                                        try {
                                                                String columnName = rsmd.getColumnName(i);
                                                                System.out.println( columnName);
                                                        } catch (SQLException e) {
                                                                System.out.println("Error reading column info for table " + tableName);
                                                                e.printStackTrace();
                                                        }
                                                }
                                        } catch (SQLException e) {
                                                System.out.println("Error reading column info for table " + tableName);
                                                e.printStackTrace();
                                        }
                                }//if listCat and listScm
                        }// while db meta data

                } catch (SQLException e) {
                        e.printStackTrace();
                }


        }


}

Edit - History - Print - Recent Changes - Search
Page last modified on November 19, 2007, at 12:37 PM