Desktop Programming > Java

Some utilities using Java 7, and 8, with new io to facilitate input /output ...

(1/3) > >>

David:
A beginning of a collection of utilities ...

For Java 7 and Java 8 ...

Update: Update: please see this next link:

http://developers-heaven.net/forum/index.php/topic,2636.0.html

FREE homework help NOW available ...

You can contact me via:
http://sites.google.com/site/andeveryeyeshallseehim/home/he-comes
http://developers-heaven.net/forum/index.php/topic,2587.0.html


You also may like to see:  C SOME UTILITY functions ...

http://developers-heaven.net/forum/index.php/topic,2608.0.html

This space is reserved for code and links to code for Java 7 utility functions ... (and demo's of their use.)

After I have collected several Java 7 snippets here ...  I hope to make an index with links on this front page.

But for now, please find these little snippets of code below,  (perhaps in related usage groupings of code, on the following pages.)


Just to get started ... (please see snippets below) ...

Added (2015-01-18 for new students of java ... A first Big step in Java beyond 'Hello World' ... see Java files at bottom of this first page.)


To facilitate input from keyboard user
To bug-proof input and streamline code ...
(for many student type problems)

More.yn( 'y' ) // defaults to yes if 'y' passed in ... return type is Java boolean
TakeIn.takeInInt( msg ) // msg is prompt message ... return type is Java int
TakeIn.takeInLng( msg )  // return type is Java long
TakeIn.takeInDbl( msg )  // return type is Java double
TakeIn.takeInStr( msg ) // return type is Java String
TakeIn.takeInChr( msg ) // return type is Java char
ReadWholeFile.readFileIntoString( fname) // return type is Java String
ReadWholeFile.readFileIntoList( fname) // return type is Java List < String >
...
See additional classes, at the bottom, to facilitate reading and writing strings, arrays and lists of text files ...
where large file read times are compared for Python 3.3, C++, C and Java 7 with nio ...
(and Java 7's new io ... compares well with the C read times ... ONLY IF the files are already in cache memory ... otherwise, C is still the FASTEST, then Python, then C++ and finally Java 7 ... in this typical ratio of times on my test system 53 : 62 : 72 : 80 (see test system below)


Update 2017-11-27

Please note that class TakeInLine is my replacement for the above ...
and you can see this class ...
and examples of its use at the following link:

http://developers-heaven.net/forum/index.php/topic,2627.0.html

After just reviewing these now, several-year-old pages, I'm thinking I should start a new thread, a.s.a.p.,  featuring Java 8 usage for Beginning Java coders ... bottom up.


Added on 2015-01-18 at bottom here, for new students of Java:

A 'next step' in Java after the usual 'Hello World' first step ...

*  demos safe take in of values ... from a keyboard user
   (using Java's exception handling)
*  demos classes with static methods ...
   (See the class TakeIn ... that facilitates safe take in of values from keyboard user.) 
*  demos some examples of Java String and Char handling ...
*  demos looping using while(..) and do..while(..) ... until a (boolean) condition is met
*  demos use of if, if else, else structure
*  demos organizing a program into blocks of code to facilitate code re-use
   (See class TakeIn, class More, class ToCaps)
*  demos use of importing (access to) some Java library methods/functions that are used here
*  demos use of Java 8 lambda function
*  demos use of Java 8 parallel processing



--- Code: ---// HelloPerson.java //  // version 2015-01-18 //

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.*; // Java 8 needed //
//import java.util.Comparator; // re. old way not using lambda functions //

/**
 *  A BIG first step in Java beyond the proverbial "Hello World of Java" starting program
 */
public class HelloPerson
{
    public static void main(String[] args) throws IOException
    {
        do
        {
            List < Integer > ages = new ArrayList <> (); // Java infers types from 'left to right' //
           
            String name = null;
            while( (name = TakeIn.takeInStr( "Enter a name: " ).trim() ).length() == 0 )
            {
                System.out.printf( "%nBlank lines not accepted here ... " );
            }
            name = ToCaps.toCapsOnAllFirstLetters( name );
   
            System.out.print( "Hello " + name + " ... " );
           
            int age = 0;
            while( !validAgeRange( age = TakeIn.takeInInt( "What is your age: " ))) ; // loop until valid data entered ... //
           
            if( age != 1 )
            {
                if( (age < 10) || (age > 50) )
                    System.out.println( name.toUpperCase() + ", awesome age, being " +
                                        age + " years old ..." );
                else
                    System.out.println( name + ", that's really nice that you are only " +
                                        age + " years old!" );
            }
            else // age is 1 ... so just to demo the 'wrapper' toAllCaps method call here ... //
                System.out.println( ToCaps.toAllCaps(name) + /* just to use the 'wrapper' here */
                                    ", that's AWESOME ... BUT REALLY, you are ACTUALLY " +
            age + " year old!!!" );
            ages.add( age );
           
            float sum = age;
            while( Character.toLowerCase(TakeIn.takeInChr( "Do you have other brothers "
                                                            + "or sisters (y/n)? " )) == 'y' )
            {
                while( !validAgeRange( age = TakeIn.takeInInt( "Enter age: " ))) ; // loop until valid data entered ... //
                ages.add( age );
                sum += age;
            }
           
            // Java 8 could break up a long list to different cores to speed up processing ... //
            float newSum = ages.parallelStream().reduce((accum, item) -> accum + item).get() ;
            System.out.format( "%nParallel processed average age: %.1f%n", newSum/ages.size() );
           
           
            Collections.sort(ages);
            System.out.format( "For all the ages entered: " + ages + "%n"
                                + "the average age is %.1f%n", sum/ages.size() );
            /*                   
            // old way before java 8, also need to: import java.util.Comparator; // 
            // to sort in reverse (i.e. descending) orded of age ... //
            ages.sort( new Comparator< Integer >()
                        {
                            @Override
                            public int compare(Integer a, Integer b)
                            { return b-a; }
                        }
                     );
            */
            ages.sort( (a, b) -> b.compareTo(a) ); // Java 8 way using lambda function, for 'reverse' sort ... //
            System.out.println( "ages reversed: " + ages );
        }
        while( More.yn() ); // More.yn defaults here to 'y' ... //
    }
   
    static boolean validAgeRange( int age )
    {
        if( (age >= 1) && (age <= 965) )
            return true;
        //else ...
        System.out.printf( "%nI don't think so ... REALLY ... " );
        return false;
    }
}
--- End code ---


Uses ...

--- Code: ---// TakeIn.java //  // version 2015-01-18 //

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class TakeIn
{
    // Java's way to handle 'const' ... is by using 'static final' ...
    // bUT NOTE, that in Java, type String is already IMMUTABLE(i.e. 'final') ... //
    static String EXTRA_CHARS = "%nError! EXTRA_CHAR'S!  Invalid non-white-space char's %nare " +
                                "present that lead and/or trail the input value.%n";
    // call as: TakeIn.takeInStr( msg ) ...
    public static String takeInStr( String msg ) throws IOException
    {
        System.out.print( msg );
       
        // Create a BufferedReader using System.in ... //
        BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
        String line = "";
        try
        {
            line = br.readLine();
        }
        catch( IOException e )
        {
            //System.err.println( e );
            //System.err.printf( "%nUNEXPECTED string input error ... %n" );
            //line = ""; // default here to empty line ... //
            throw new IOException( e + " UNEXPECTED error attempting string input!" );
        }
        //line = line.trim();
        return line;
    }
 
 
    // call as: TakeIn.takeInChr( msg )
    public static char takeInChr( String msg ) throws IOException
    {   
        String line = takeInStr( msg );
        if( line.length() > 0 )
            return (char)line.charAt(0);
        // else ...
        return (char)0; 
    } 


       
    // call as: TakeIn.takeInInt( msg )
    public static int takeInInt( String msg ) throws IOException
    {   
        int iVal = 0;
        boolean done = false;
        while( !done )
        {
            String line = takeInStr( msg ).trim();
            String[] ary =  line.split( "[ \t]+" );
     
            if( ary.length == 1 )
            {
                try
                {
                    iVal = Integer.parseInt( ary[0] );
                    done = true;
                }
                catch( NumberFormatException e )
                {
                    System.out.printf( "%nError! " + e );
                    System.out.printf( "%nOnly valid 'int' numbers are accepted, so try again ...%n%n" );
                }
            }
            else System.out.printf( EXTRA_CHARS );
        }
        return iVal;
    }
   

    // call as: TakeIn.takeInLng( msg )
    public static long takeInLng( String msg ) throws IOException
    {   
        long longVal = 0;
        boolean done = false;
        while( !done )
        {
            String line = takeInStr( msg ).trim();
            String[] ary =  line.split( "[ \t]+" );

            if( ary.length == 1 )
            {
                try
                {
                    longVal = Long.parseLong( ary[0] );
                    done = true;
                }
                catch( NumberFormatException e )
                {
                    System.out.printf( "%nError! " + e );
                    System.out.printf( "%nOnly valid 'long' numbers are accepted, so try again ...%n%n" );
                }
            }
            else System.out.printf( EXTRA_CHARS );
        }
        return longVal;
    }
   
   
    // call as: TakeIn.takeInDbl( msg ) ...
    public static double takeInDbl( String msg ) throws IOException
    {   
        double dVal = 0;
        boolean done = false;
        while( !done )
        {
            String line = takeInStr( msg ).trim();
            String[] ary =  line.split( "[ \t]+" );

            if( ary.length == 1 )
            {
                try
                {
                    dVal = Double.parseDouble( ary[0] );
                    done = true;
                }
                catch( NumberFormatException e )
                {
                    System.out.printf( "%nError! " + e );
                    System.out.printf( "%nOnly valid 'double' numbers are accepted, so try again ...%n%n" );;
                }
            }
            else System.out.printf( EXTRA_CHARS );
        }
        return dVal;
    }
}
--- End code ---


Also uses ...

--- Code: ---// ToCaps.java //  // version 2015-01-18 //

public class ToCaps
{
    public static String toCapsOnAllFirstLetters( String str )
    {
        boolean prevWasWS = true;
        char[] chars = str.toCharArray();
        for( int i = 0; i < chars.length; ++i )
        {
            if( Character.isLetter( chars[i]) )
            {
                if( prevWasWS )
                {
                    chars[i] = Character.toUpperCase( chars[i] );   
                }
                prevWasWS = false;
            }
            else prevWasWS = Character.isWhitespace( chars[i] );
        }
        return new String( chars );
    }
   
    public static String toAllCaps( String str ) // can just use str.toUpperCase() //
    {
        return str.toUpperCase();
    }
   
    public static String toCapsOnFirstLetter( String str )
    {
        if( str.length() > 0 )
        {
            char[] chars = str.toCharArray();
            chars[0] = Character.toUpperCase( chars[0] );
            return new String( chars );
        }
        /*
        if( str.length() > 0 )
            return Character.toUpperCase(str.charAt(0))
                    + str.substring(1);
        */
        // else ...
        return str;
    }
}
--- End code ---


And now the 4th ... last file needed here:

--- Code: ---// More.java //  // 2015-01-18 //

import java.io.InputStreamReader;
import java.io.BufferedReader;

public class More
{
    // call as:  More.yn( 'y' ) // or 'n' if want no as defaultChar ... //
    public static boolean yn( final char defaultChar ) // 'y' or 'n' tells 'defaultChar' ... //
    {
        System.out.print( "More (y/n) ? " ) ;

        // Create a BufferedReader using System.in
        BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
        String reply = null;
        try
        {
            reply = br.readLine();
        }
        catch( Exception e )
        {
            System.out.printf( "%nAn unexpected ERROR during String input!%n" + e );
            //System.out.printf( "%nExiting loop ... %n" );
            reply = "n"; // default here to NO ... //
        }

        // NEED these ... //
        if( defaultChar == 'y' )
        {
            if( reply.length() == 0 ) return true;
            if( Character.toLowerCase(reply.charAt(0)) == 'n' ) return false;
            return true;
        }
        // else ...
        if( defaultChar == 'n' )
        {
            if( reply.length() == 0 ) return false;
            if( Character.toLowerCase(reply.charAt(0)) == 'y' ) return true;
            return false;
        }
        // else ... defaults to YES ...
        return true;       
    }

    // call as:  More.yn()
    // this defaults to 'y' ... i.e. yes more ... //
    public static boolean yn() // defaults to yes/y //
    {
        return yn( 'y' );
    }
   
}
--- End code ---

Enjoy :)

David:
Ok ... first the build / run batch file and the little test program ...

Firstly the batch file ... give it a name ending in .bat

You could name the batch file: buildRunTestTakeIn.bat

NOTE!  This batch file compiles to java byte code the 3 files below. (See inside the batch file to make sure the file names there match your 3 file names below!!!)


--- Code: ---@echo off

rem path

javac TestTakeIn.java

dir *.class

pause

java TestTakeIn

pause
--- End code ---


Now name this file: TestTakeIn.java


--- Code: ---// file name: TestTakeIn.java //  // 2013-09-10 //

public class TestTakeIn
{
    public static void main( String[] args )
    {
        boolean allOk = false;
        do
        {
            int iVal = 0;
            long longVal = 0;
            double dVal = 0.0;
            String sVal = "";
            char cVal = 0;
           
            try
            {
                iVal =    TakeIn.takeInInt( "Enter a valid integer :  " );
                longVal = TakeIn.takeInLng( "Enter a valid 'long'  :  " );
                dVal =    TakeIn.takeInDbl( "Enter a valid decimal :  " );
                sVal =    TakeIn.takeInStr( "Enter a line of text  :  " );
                cVal =    TakeIn.takeInChr( "Enter a char          :  " );
                allOk = true;
            }
            catch( Exception e )
            {
                System.err.println( e );
                System.err.println( "EXITING PROGRAM NOW ..." );
                allOk = false;
            }
            finally
            {
                if( !allOk ) break;
            }

            // test remainder ...
            if( iVal % 2 == 0 )
                System.out.println( iVal + " is an even number." );
            else
                System.out.println( iVal + " is an odd number." );
               
            System.out.println( longVal + " was your long number." );
           
            System.out.println( dVal + " was your decimal number." );
            // using C style 'printf' formatting ... to ALWAYS show ...
            // 2 decimal places ... //
            System.out.printf( "%.2f was your decimal number formatted.%n", dVal );
            // or ...
            System.out.format( "%.2f was your decimal number formatted.%n", dVal );
           
            System.out.println( "'" + sVal + "' was your 'text'." );
           
            System.out.println( "'" + cVal + "' was your 'char'." );           
        }
        while( More.yn( 'y' ) ); // defaults to 'y' ... //
    }
}
--- End code ---

David:
Ok ... now the TakeIn's ...

(needed by the above test program) ...

Name this file: TakeIn.java
(See test program "TestTakeIn.java" above to see usage.)

Edit: the file "TakeIn.java" is now available here ...

http://developers-heaven.net/forum/index.php/topic,2612.0.html

David:
Now ... the 3rd java file ... a handy student utility ...

Name this file: More.java
(See test program "TestTakeIn.java" above to see usage.)

Edit: the file "More.java" is now available here ...

http://developers-heaven.net/forum/index.php/topic,2612.0.html

David:
Now some file reading utilities ...

1. to read whole file into one big Java String

2. to read whole into a list of lines (Java Strings)


First a little test program with a batch file to compile and run the test program with the 'class ReadWholeFile'


You could name this next batch file:  "buildRun.bat"


--- Code: ---@echo off

javac  TestReadWholeFile.java

dir *.class

pause

java TestReadWholeFile

pause
--- End code ---


Now the test program:


--- Code: ---// TestReadWholeFile //  // 2013-09-11 //

import java.io.IOException;
import java.util.Scanner;
import java.util.List;

class TestReadWholeFile
{
    public static void main( String[] args ) throws IOException
    {
        String fname = "TestReadWholeFile.java";
       
        String s = ReadWholeFile.readFileIntoString( fname ); // returns new 's' with ALL file contents
       
        Scanner sc = new Scanner( s );
        while( sc.hasNextLine() )
            System.out.println( sc.nextLine() );
           
        List < String > myFileLines = ReadWholeFile.readFileIntoList( fname );
        int totCharCount = 0;
        for( String line: myFileLines )
        {
            totCharCount += line.length();
            System.out.println( line.trim() );
        }
        System.out.println( "Average number of char's per line was: " +
                        ((int) ((float)totCharCount/myFileLines.size()+.5) ) );
       
    }
}
--- End code ---

Navigation

[0] Message Index

[#] Next page

Go to full version