Author Topic: Some utilities using Java 7, and 8, with new io to facilitate input /output ...  (Read 16772 times)

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
A beginning of a collection of utilities ...

For Java 7 and Java 8 ...





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: [Select]
// 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;
    }
}


Uses ...
Code: [Select]
// 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;
    }
}


Also uses ...
Code: [Select]
// 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;
    }
}


And now the 4th ... last file needed here:
Code: [Select]
// 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' );
    }
   
}

Enjoy :)
« Last Edit: December 01, 2017, 05:24:14 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate student type keyboard
« Reply #1 on: September 05, 2013, 07:43:38 AM »
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: [Select]
@echo off

rem path

javac TestTakeIn.java

dir *.class

pause

java TestTakeIn

pause


Now name this file: TestTakeIn.java

Code: [Select]
// 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' ... //
    }
}
« Last Edit: November 15, 2014, 09:21:25 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate student type keyboard
« Reply #2 on: September 05, 2013, 07:46:57 AM »
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
« Last Edit: January 01, 2015, 08:34:53 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate student type keyboard
« Reply #3 on: September 05, 2013, 07:54:00 AM »
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
« Last Edit: January 01, 2015, 08:37:01 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate reading files
« Reply #4 on: September 11, 2013, 09:54:03 AM »
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: [Select]
@echo off

javac  TestReadWholeFile.java

dir *.class

pause

java TestReadWholeFile

pause


Now the test program:

Code: [Select]
// 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) ) );
       
    }
}
« Last Edit: November 15, 2014, 09:23:23 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate reading files
« Reply #5 on: September 11, 2013, 09:55:42 AM »
Now here is the class used in the above test program ...


Code: [Select]
// ReadWholeFile.java //   // 2013-09-11 //

//1. to read whole file into one big Java String
// or ...
//2. to read whole into a list of lines (Java Strings)

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;


public class ReadWholeFile
{
    public static void readFile( File f, StringBuffer buf ) throws IOException
    {
        try( BufferedReader br = new BufferedReader( new FileReader( f )) )
        {
            char[] cbuf = new char[ (int)f.length() ];
            br.read(cbuf); 
            buf.append(cbuf);
        }
    }
   
    // call using ... ReadWholeFile.readFileIntoString( fname );
    public static String readFileIntoString( final String fname )
                                                throws IOException
    {
        File f = new File( fname );
        StringBuffer sb = new StringBuffer( new StringBuilder() );
       
        readFile( f, sb );
        return new String( sb );
    }
   
    // call using ... ReadWholeFile.readFileIntoList( fname, avgNumCharsPerLine );
    public static List < String > readFileIntoList( final String fname,
                                            int lineSize ) throws IOException
    {
        File f = new File( fname );
   
        try( BufferedReader br = new BufferedReader( new FileReader( f )) )
        {
            List < String > myLst = new ArrayList <> ( (int)f.length() /lineSize );
            String line = null;
            while( ( line = br.readLine() ) != null )
                myLst.add( line );
            return myLst;
        }   
    }
   
    // call using ... ReadWholeFile.readFileIntoList( fname );
    public static List < String > readFileIntoList( final String fname )
                                                    throws IOException
    {
        return readFileIntoList( fname, 60 );
    }
}
« Last Edit: November 15, 2014, 09:24:34 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #6 on: September 16, 2013, 05:09:17 AM »
Here is an often wanted student utility class that gets a new Java String 'With Caps On All First Letters' ...


Firstly, a little test program
Code: [Select]
import java.util.Scanner;

public class TestToCapsOnAllFirstLetters
{
    public static void main( String[] args )
    {     
        try( Scanner sc = new Scanner(System.in) )
        {
            final String prompt = "Enter name(s) & number (separated by ws - "+
                                    " Blank line to quit) : ";
            String line;
            System.out.print( prompt );
            while( sc.hasNextLine() && !( line = sc.nextLine() ).equals( "" ))
            {
                String[] toks = line.trim().split( "\\s+" ); // split on any 'ws'
                String name = toks[0];
                boolean numOk = false;
                int num = 0;
                int i = 1;
                while( i < toks.length && !numOk )
                {
                    try
                    {
                        num = Integer.parseInt(toks[i]);
                        numOk = true;
                    }
                    catch( NumberFormatException e )
                    {
                        name += " " + toks[i];
                    }

                    ++i;
                    if( i == toks.length && !numOk )
                    {
                        System.out.println( "Try again ..." );
                        break;
                    }   
                }
                if( numOk )
                    System.out.println( "Your number '" +
                        ToCapsOnAllFirstLetters.toCapsOnAllFirstLetters( name ) +
                        "' was '" + num + "'" );

                System.out.print( prompt );
            }
        }
        //sc.close();
        System.out.println( "Done" );
    }
}


Now the class file ...

Code: [Select]
public class ToCapsOnAllFirstLetters
{
    public static String toCapsOnAllFirstLetters( final 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 );
    }
}


Now classes to get a comma formatted string for a long number and to get int powers of an int ...
(Note: comma formatted numbers are readily available in Java by using printf(..) or print.format(..)
           by addind a comma as per the following example:
           Console.out.printf( "The number with commas is %,d", intNum );
           Console.out.println(); )

Firstly, the test program ...

Code: [Select]
class TestCommaFormat
{
    public static void main( String[] args )
    {
        for( int p = 32; p >= 0; --p )
        {
            System.out.printf( "Formatted Power.pow(-2, %d) = %s", p,
                                CommaFormat.formatWithCommas(Power.pow(-2, p)) );
            System.out.println( " vs " + Power.pow(-2, p) );
        }
    }
}


Then the two classes ...

Code: [Select]
public class Power
{
    public static long pow( int base, int p )
    {
        long prod = 1;
        for( int i = 0; i < p; ++i )
            prod *= base;
        return prod;
    }
}

And ...

Code: [Select]
import java.util.Arrays;

public class CommaFormat
{
    public static String formatWithCommas( long i )
    {
        final String iStr = "" + i;
        int len = iStr.length();
        boolean hasSign = iStr.charAt(0) == '-' || iStr.charAt(0) == '+';
        if( hasSign ) --len;
        char[] fmtAry = new char[ len + (len-1)/3 ];
        Arrays.fill( fmtAry, ',' );
        for( int j = len-1 +(hasSign ? 1: 0), k = fmtAry.length-1, cnt = 0; k >= 0; --j, --k )
        {
            fmtAry[k] = iStr.charAt(j);
            if( ++cnt % 3 == 0 ) --k;
        }
        String iFmtStr = new String( fmtAry );
        if( hasSign ) iFmtStr = iStr.charAt(0) + iFmtStr;
        return iFmtStr;
    }
}[/code
« Last Edit: January 01, 2015, 08:45:26 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #7 on: September 16, 2013, 05:12:33 AM »
This is an example of a File Read Write Class ... (see the next 3 .java files)
 
First the little test program, that presumes you already have a text file  ...

C:\tmp\test1.txt

that has a few short lines of text


You will need all 3 java file/programs that follow, to use this 1st file, the 'test' program file ...

Code: [Select]
//package textfiles;

/*
 * This test program presumes you already have a text file
 * holding a few lines of text, called test1.txt
 * with (Windows) path c:\tmp\test1.txt
 *
 */

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

public class TestReadWriteFile
{
    public static void main( String[] args ) throws IOException
    {
        String fname = "c:/tmp/test1.txt";
        System.out.format( "Testing readFileIntoStringArray ... %n" );
        //String[] aryLines = null;
        try
        {
            //ReadFile rf = new ReadFile( fname );
            //String[] aryLines = rf.readFileIntoStringArray();
            String[] aryLines = ReadFile.readFileIntoStringArray( fname );
            for( String line: aryLines )
                System.out.println( line );
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
       
        System.out.format( "%nTesting readFileIntoString ... %n" );
        try
        {
            String bigString = ReadFile.readFileIntoString( fname );
            System.out.println( bigString );
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
       
        List < String > myLst = null;
        System.out.format( "%nTesting readFileIntoList ... %n" );
        try
        {
            myLst = ReadFile.readFileIntoList( fname );
            for( String line: myLst )
                System.out.println( line );
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
       
       
        // Write to File //
        System.out.format( "%nTesting writeLineToFile (appending) ... %n" );
        String line = "The quick brown fox jumped through the hole in the fence.";
        try
        {
            //WriteFile wf = new WriteFile( fname, true ); // true = append
            //wf.writeLineToFile( line );
            WriteFile.writeLineToFile( fname, line, true ); // true = append //
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
       
        try
        {
            String longLine = ReadFile.readFileIntoString( fname ); // false = append //
            System.out.println( longLine );
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
       
       
        try
        {
            //WriteFile wf = new WriteFile( fname, true ); // true = append
            //wf.writeLineToFile( line );
            WriteFile.writeListToFile( fname, myLst ); // false = append //
        }
        catch( IOException e )
        {
            System.err.println( e.getMessage() );
        }
    }
}


Now the two files with the file read and file write classes and methods ...


Code: [Select]
//package textfiles;

import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

import java.io.File;

import java.util.ArrayList;
import java.util.List;


public class ReadFile
{
    private String path = null;
   
    public ReadFile( String path )
    {
        this.path = path;
    }
   
    public String[] readFileIntoStringArray() throws IOException
    {
        FileReader fr = new FileReader( path );
        String[] data;
        try( BufferedReader br = new BufferedReader( fr ) )
        {
            int numOfLines = readLines();
           
            data = new String[ numOfLines ];
            int i = 0;
            for( ; i < numOfLines; ++i )
                data[i] = br.readLine();
        }
        return data;
    }
   
    public static String[] readFileIntoStringArray( String path ) throws IOException
    {
        ReadFile rf = new ReadFile( path );
        return rf.readFileIntoStringArray();
    }
   
    int readLines() throws IOException
    {
        FileReader fr = new FileReader( path );
        int numOfLines;
        try( BufferedReader br = new BufferedReader( fr ) )
        {
            numOfLines = 0;
            String line = null;
            while( ( line = br.readLine() ) != null ) ++ numOfLines;
        }
        return numOfLines;
    }
   
   

    //1. to read whole file into one big Java String
    // or ...
    //2. to read whole file into an ArrayList of lines (Java Strings)

    private static final int AVG_NUM_CHARS_ON_LINE = 30;
   
    public static void readFileChars( File f, StringBuffer buf ) throws IOException
    {
        try( BufferedReader br = new BufferedReader( new FileReader( f )) )
        {
            char[] cbuf = new char[ (int)f.length() ]; // f.length() returns 'long'
            br.read( cbuf ); 
            buf.append( cbuf );
        }
    }
   
    // call using ... ReadWholeFile.readFileIntoString( fname );
    public static String readFileIntoString( final String fname )
                                                throws IOException
    {
        File f = new File( fname );
        StringBuffer sb = new StringBuffer( new StringBuilder() );
        readFileChars( f, sb );
        return new String( sb );
    }
   
    // call using ... ReadWholeFile.readFileIntoList( fname, avgNumCharsPerLine );
    public static List < String > readFileIntoList( final String fname,
                                            int lineLen ) throws IOException
    {
        File f = new File( fname );
   
        try( BufferedReader br = new BufferedReader( new FileReader( f )) )
        {
            List < String > myLst = new ArrayList <> ( 1 + (int)f.length() / lineLen );
            String line = null;
            while( ( line = br.readLine() ) != null )
                myLst.add( line );
            return myLst;
        }   
    }
   
    // call using ... ReadWholeFile.readFileIntoList( fname );
    public static List < String > readFileIntoList( final String fname )
                                                    throws IOException
    {
        return readFileIntoList( fname, AVG_NUM_CHARS_ON_LINE );
    }
}


And ...


Code: [Select]
//package textfiles;

import java.io.IOException;
import java.io.FileWriter;
import java.io.PrintWriter;

import java.util.List;
       
public class WriteFile
{
    private String path;
    boolean appendToFile = false;
   
    public WriteFile( final String path )
    {
        this.path = path;
    }
   
    public WriteFile( final String path, boolean appendVal )
    {
        this.path = path;
        appendToFile = appendVal;
    }
   
    public void writeLineToFile( final String line ) throws IOException
    {
        FileWriter fw = new FileWriter( path, appendToFile );
        try( PrintWriter pw = new PrintWriter( fw ) )
        {
            pw.printf( "%s%n", line );
        }
    }
   
    /**
     *
     * @param fname
     * @param line
     * appendVal
     * @throws IOException
     */
    public static void writeLineToFile( final String fname, final String line, boolean appendVal  )
                                                            throws IOException
    {
        WriteFile wf = new WriteFile( fname, appendVal );
        wf.writeLineToFile( line );
    }
   
    /**
     *
     * @param fname
     * @param line
     * @throws IOException
     */
    public static void writeLineToFile( final String fname, final String line )
                                                            throws IOException
    {
        WriteFile wf = new WriteFile( fname );
        wf.writeLineToFile( line );
    }
   
    /**
     *
     * @param fname
     * @param String[] lines
     * appendVal
     * @throws IOException
     */
    public static void writeArrayToFile( final String fname,
                                    final String[] lines, boolean appendVal  )
                                                            throws IOException
    {
        FileWriter fw = new FileWriter( fname, appendVal );
        try( PrintWriter pw = new PrintWriter( fw ) )
        {
            for( String line: lines )
                pw.printf( "%s%n", line );
        }
    }
   
    /**
     *
     * @param fname
     * @param String[] lines
     * @throws IOException
     */
    public static void writeArrayToFile( final String fname,
                                    final String[] lines  ) throws IOException
    {
        writeArrayToFile( fname, lines, false );
    }

    /**
     *
     * @param fname
     * @param String[] lines
     * appendVal
     * @throws IOException
     */
    public static void writeListToFile( final String fname,
                                    final List < String> lines, boolean appendVal  )
                                                            throws IOException
    {
        FileWriter fw = new FileWriter( fname, appendVal );
        try( PrintWriter pw = new PrintWriter( fw ) )
        {
            for( String line: lines )
                pw.printf( "%s%n", line );
        }
    }
   
    /**
     *
     * @param fname
     * @param String[] lines
     * @throws IOException
     */
    public static void writeListToFile( final String fname,
                                    final List < String > lines  ) throws IOException
    {
        writeListToFile( fname, lines, false );
    }

}
« Last Edit: November 15, 2014, 09:25:32 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #8 on: September 19, 2013, 01:56:42 PM »
This next section will feature, finally, the nio in Java 7 for TEXT file io ...

AND ...

HERE we will compare the speed of Java 7's new io for file input with C vs C++ vs Python 3.3.2 ...

All programs will read the same randomly generated, 100,000 paragraph, BIG TEXT file.

0. Firstly, a little Python 3.3.2 program to generate our BIG text file ...

1. Then the Python program to read that BIG TEXT file and report the times ...

2. Then a C++ program to read that BIG TEXT file and report the times ...

3. Then a C program to to read that BIG TEXT file and report the times ... that uses C's fgets ...
    (This C program uses the custom C files: readLine.h and Cvec.h, see links)

4. Finally ... the Java 7 test program file with a separate class file holding the new read/write's following ...

AND ... a NICE surprise ... the Java 7 new io (in nio) file (cache) read times ... when reading files already in cache memory ... were a little faster than the C program that used fgets and a large fixed buffer to read each line into a dynamic array using Cvec and push_backCvec

The C++ (file already in cache) read times were about 50% longer ... and the Python (file already in cache) read times were in the middle.

So ... it does really look like ... the new Java 7 file io (in nio) ... will be a big plus for Java these days ...

BUT NOTE:  Java 7 nio seems optimized to read files ***already in cache memory***, and Java 7 nio WAS THE SLOWEST to ready the BIG FILES that were NOT already in cache memory ...

See these typical 'first read times'  (for my randomly generated 100,000 paragraph BIG TEXT file) ...

AND NOTE how WELL the Python 'first read times' compare with the C 'first read times' , (even faster than the C++ 'first read times') ...

(Java 7 :  0.80 )  vs  (C++ :  0.72)  vs  (Python 3.3.2 :  0.62)  vs  (C :  0.53)



Here is a table of 3 sets (of averages of) my (typical) results (run on my 64 bit Win 7 OS laptop):

Python 3...
Average times were 0.61, 0.70 ... (first time 0.62)
0.066 was average time for finding maxLineLen = 1599
Average times were 0.61, 0.70 ... (first time 0.64)
0.066 was average time for finding maxLineLen = 1599
Average times were 0.61, 0.71 ... (first time 0.62)
0.059 was average time for finding maxLineLen = 1599


C++...
Average time was 0.71 seconds (first time 0.72)
Average time to get max line length 1599 char's was 0.003000 seconds
Average time was 0.72 seconds (first time 0.72)
Average time to get max line length 1599 char's was 0.003000 seconds
Average time was 0.71 seconds (first time 0.72)
Average time to get max line length 1599 char's was 0.003200 seconds


C...
Average time was: 0.51 (first time 0.51) Longest line in file had 1599 char's.
Average time was: 0.50 (first time 0.51) Longest line in file had 1599 char's.
Average time was: 0.52 (first time 0.56) Longest line in file had 1599 char's.


Java 7...
Average times were 0.492, 4.124 (first time 0.80)
Average time to find maxLineLen of 1599 was 0.015
Average times were 0.446, 4.608 (first time 0.77)
Average time to find maxLineLen of 1599 was 0.013
Average times were 0.476, 3.977 (first time 0.83)
Average time to find maxLineLen of 1599 was 0.011




Ok ... the Python 3... BIG TEXT file generation program ...


Code: [Select]
# genLongTextFile.py #  # 2013-09-19 #

from random import *

import sys

lets = 'zyxwvutsrqponmlkjihgfedcba'
MAX_WORD_LEN = 16

def word( length ):
    w = ''
    for i in range( 1, length+1 ):
        w += lets[ randrange( len(lets) ) ]
    return w

def sentence( length ):
    lst = []
    for i in range( randrange( 3, length+1) ):
        lst.append( word( randrange( 1, MAX_WORD_LEN )))
    s = ' '.join( lst )
    return s[0:1].upper() + s[1:] + '.'

def paragraph( pLen, sLen ):
    lst = []
    for i in  range( 1, pLen +1 ):
        lst.append( sentence( sLen ) )
    return '  '.join( lst ) + '\n\n'
   

with open( 'longTextFile.txt', 'w' ) as f:
    print( 'Creating file \'longTextFile.txt\' with 100,000 paragraphs ...' )
    for i in range( 100000 ):
        if (i+1) % 1000== 0:
            print( i+1, end = ' ' )
            sys.stdout.flush()
        f.write( paragraph( 7, 25 ) )


input( "Done ... Press 'Enter' to continue/exit ... " )


Now the 'timed test' Python 3 program ...

Code: [Select]
# testTimesToRead.py #  # 2013-09-22 #

import datetime as dt

FNAME = 'longTextFile.txt'


NUM_LOOPS = 5
loops = NUM_LOOPS
sum1, sum2 = 0.0, 0.0
while( loops ):
    t1 = dt.datetime.now()
    with open( FNAME ) as f:
        lst = f.readlines()   
    t2 =dt.datetime.now()
    sum1 += (t2-t1).total_seconds()
    print( (t2-t1).total_seconds(), \
           "was for 'lst = r.readlines()'" )

    t1 = dt.datetime.now()
    with open( FNAME ) as f:
        x = f.read()
        lst = x.splitlines()
    t2 =dt.datetime.now()
    sum2 += (t2-t1).total_seconds()
    print( (t2-t1).total_seconds(), \
           "was for 'x.read(); lst = x.splitlines()'" )

    loops -= 1
   
print( '\nAverage times were %.2f, %.2f ...' \
       % ( sum1 / NUM_LOOPS, sum2 / NUM_LOOPS ) );

   

print()   
loops = NUM_LOOPS
t1 = dt.datetime.now()
while( loops ):
    maxLineLen = 0
    for line in lst:
        if len(line) > maxLineLen:
            maxLineLen = len(line)
    loops -= 1
   
t2 =dt.datetime.now()

print( "%.3f" % ( (t2-t1).total_seconds() / NUM_LOOPS ), \
       'was average time for finding ' \
       + 'maxLineLen =', maxLineLen )



print()
input( "Press 'Enter' to continue/exit ... " )
« Last Edit: November 15, 2014, 09:26:01 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #9 on: September 19, 2013, 02:04:05 PM »
Now the C++ program ...

Code: [Select]
/* testRead_cpp.cpp */  /* 2013-09-21 */

#include <cstdio>
#include <ctime>

#include <fstream>
#include <string>
#include <vector>

using namespace std;



bool fillVecFromFile( vector < string >& v, const string& fname )
{
    ifstream fin( fname.c_str() );
    if( fin )
    {
        string line;
        while( getline( fin, line ) )
            v.push_back( line );
        fin.close();
        return true;
    }
    //else ...
    return false;
}

size_t getMaxLineLen( const vector < string >& v )
{
    size_t maxLen = 0;
    for( int i = v.size() -1; i >= 0; -- i )
    {
        if( v[i].length() > maxLen ) maxLen = v[i].length();
    }
    return maxLen;
}


int main()
{
    double tf, ti;
    double sum1 = 0.0;
    int maxLoops = 5;
    int loops = maxLoops;
   
    vector< string > v;
    while( loops )
    {
        ti = clock();
        v.clear();
        fillVecFromFile( v, "longTextFile.txt" );
        tf = clock();
        sum1 += tf-ti;
        printf( "Elapsed time was %f seconds\n", (tf-ti)/CLOCKS_PER_SEC );
        --loops;
    }
   
    printf( "\nAverage time was %.2f seconds\n", sum1/maxLoops/CLOCKS_PER_SEC );

    printf( "v.size() = %u, v.capacity = %u\n", (unsigned)v.size(),
                                             (unsigned)v.capacity() );
   
    loops = maxLoops;
    unsigned maxLen;
    ti = clock();
    while( loops )
    {
         maxLen = getMaxLineLen( v );
         --loops;
    }
    tf = clock();
   
    printf( "\nAverage time to get max line length was %f seconds\n",
                                    (tf-ti)/CLOCKS_PER_SEC/maxLoops  );
    printf( "Longest line in file had %u char's.\n", maxLen );
   
   
    printf( "\nPress 'Enter' to continue/exit ... " );
    fflush( stdout );
   
    getchar();
}
« Last Edit: November 15, 2014, 09:26:30 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #10 on: September 19, 2013, 02:06:56 PM »
Here is the C test program ... see links for 2 include files needed  ...


Cvec.h
http://developers-heaven.net/forum/index.php/topic,2580.msg2862.html#msg2862

readLine.h
http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864


Code: [Select]
/* testRead_c.c */  /* 2013-09-22 */

#include "readLine.h" /* see file to see all the includes, etc... */
#include <time.h>

typedef struct
{
   char* str;
} Rec ;


void freeVrec( Rec* r )
{
   free( r->str );
}

/* Ok ... now can include ... */
#include "Cvec.h"


int fillCvecFromFile( Cvec* cv, const char* fname )
{
    static char buf[1024*4] ;
   
    FILE* fin = fopen( fname, "r" );
    if( fin )
    {
        Rec rc;
        int len = 0, maxLen = 0;
        /*while( ( rc.str = readLine( fin ) ) ) */
        while( fgets( buf, sizeof(buf), fin ) != NULL  )
        {
            len = strlen( buf );
            if( len && buf[len-1] == '\n' ) buf[--len] = 0;

            rc.str = malloc( len+1 );
            myAssert( (rc.str != NULL), "Error ... malloc failed!!!" );
            strcpy( rc.str, buf );
            push_backCvec( cv, &rc );

            if( len > maxLen ) maxLen = len;
        }
        fclose( fin );
        return maxLen;
    }
    /* else ... */
    return -1; /* flag value for FILE open error ... */
}


int main()
{
    const char* fname = "longTextFile.txt";
    double sumTimes = 0.0;
    double tf, ti;
    int maxLoops = 5;
    int loops = maxLoops;
    int maxLineLen = 0;
    Cvec cv;
    initCvec( &cv );
    while( loops )
    {
        clearCvec( &cv );
        ti = clock();
        maxLineLen = fillCvecFromFile( &cv, fname );
        tf = clock();
        printf( "Elapsed time was %f seconds\n", (tf-ti)/CLOCKS_PER_SEC );
        sumTimes += (tf-ti);
        --loops;
    }
   
    printf( "\nAverage time was: %.2f\n", sumTimes/CLOCKS_PER_SEC/maxLoops );
    printf( "cv.size = %d, cv.cp = %d\n", cv.size, cv.cap );
   
    printf( "Longest line in file had %d char's.\n", maxLineLen );
    printf( "\nPress 'Enter' to continue/exit ... " );
    fflush( stdout );
   
    getchar();
    clearCvec( &cv );
    return 0;
}
« Last Edit: January 01, 2015, 04:06:36 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output
« Reply #11 on: September 19, 2013, 02:34:53 PM »
Now the Java 7 test program ...


Code: [Select]
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;

import java.util.ArrayList;
import java.util.List;

import java.util.Scanner;

public class TestTextFilesJ7
{
    final static String IN_FNAME = "longTextFile.txt";
    final static String OUT_FNAME = "output.txt";
    final static Charset ENCODING = StandardCharsets.UTF_8;
    final static double TEN_POW9 = 1_000_000_000.0;

    public static void main( String[] args ) throws IOException
    {
        List < String > myLst = new ArrayList <> ();
        final int MAX_LOOPS = 5;
        int loops = MAX_LOOPS;
        long t1, t2, sumTimes1 = 0, sumTimes2 = 0;
       
        while( loops > 0 )
        {
            System.out.println( "TextFilesJ7.readTextFileReadLine ... " );
            t1 = System.nanoTime();
            myLst.clear();
            myLst = TextFilesJ7.readTextFileReadLine( IN_FNAME );
            t2 = System.nanoTime();
            sumTimes1 += t2-t1;
            System.out.println( "Elapsed time was " +
                                            (t2-t1)/TEN_POW9 + " seconds" );
                                           
            System.out.println( "TextFilesJ7.readTextFileScanLine ... " );
            t1 = System.nanoTime();
            myLst.clear();
            myLst = TextFilesJ7.readTextFileScanLine( IN_FNAME, ENCODING );
            t2 = System.nanoTime();
            sumTimes2 += t2-t1;
            System.out.println( "Elapsed time was " + (t2-t1)/TEN_POW9 + " seconds" );
       
            --loops;
        }
       
        System.out.println();
        System.out.format( "Average times were %.3f, %.3f%n", 
            sumTimes1/TEN_POW9/MAX_LOOPS, sumTimes2/TEN_POW9/MAX_LOOPS );
       
       
        System.out.format( "%nTextFilesJ7.writeTextFile ... %n" );
        t1 = System.nanoTime();
        TextFilesJ7.writeTextFile( OUT_FNAME, myLst );
        t2 = System.nanoTime();
        System.out.println( "Elapsed time was " + (t2-t1)/TEN_POW9 + " seconds" );
           
           
        System.out.println( "myLst.size() = " + myLst.size() );
       
        t1 = System.nanoTime();
        int maxLineLen = 0;
        for( int i = 0; i < MAX_LOOPS; ++ i )
        {
            for( String line: myLst )
            {
                if( line.length() > maxLineLen ) maxLineLen = line.length();
            }
        }
        t2 = System.nanoTime();
        System.out.format( "Average time to find maxLineLen of %d was %.3f%n",
                                    maxLineLen, (t2-t1)/TEN_POW9/MAX_LOOPS );
       
       
        System.out.format( "%nPress 'Enter' to continue/exit ... " );
        Scanner sc = new Scanner( System.in );
        String dummy = sc.nextLine();
    }

}


And the class used above ...

Code: [Select]
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;



public class TextFilesJ7
{
    public static List < String > readTextFileScanLine( final String fname,
                                        final Charset cs ) throws IOException
    {
        Path pth = Paths.get( fname );
        List < String > lst = null;
        try( Scanner sc =  new Scanner( pth, cs.name() ) )
        {
            lst = new ArrayList <>();
            while( sc.hasNextLine() )
                lst.add( sc.nextLine() );
               
        }
        return lst;
    }
 
    public static List < String > readTextFileReadLine( final String fname,
                                        final Charset cs ) throws IOException
    {
        Path pth = Paths.get( fname );
        List < String > lst = null;
        try ( BufferedReader br = Files.newBufferedReader( pth, cs ) )
        {
            String line = null;
            lst = new ArrayList <>();
            while( ( line = br.readLine() ) != null )
                lst.add( line );     
        }
        return lst;
    }
   
    public static List < String > readTextFileReadLine( final String fname )
                                                            throws IOException
    {
        return readTextFileReadLine( fname, StandardCharsets.UTF_8  );
    }
 
    public static void writeTextFile( final String fname,
        final List < String > lstLines, final Charset cs ) throws IOException
    {
        Path pth = Paths.get( fname );
        try( BufferedWriter bw = Files.newBufferedWriter( pth, cs ) )
        {
            for( String line : lstLines )
            {
                bw.write( line );
                bw.newLine();
            }
        }
    }
   
    public static void writeTextFile( final String fname,
                            final List < String > lstLines ) throws IOException
    {
        writeTextFile( fname, lstLines, StandardCharsets.UTF_8 );
    }

}
« Last Edit: January 01, 2015, 08:22:48 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Re: Some utilities using Java 7 with new io to facilitate input /output ...
« Reply #12 on: December 22, 2014, 10:36:37 AM »
See new first steps in Java ... added to top page here ...

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

for now ...


And here is an other beginner type Java example that illustrates using several classes and using inheritance as per the class Employee being derived here from the super class Person ... so that it inherits from class Person ...

Put all these next 6 files in a single folder and call:
javac Payroll.java

Then ... you can call (after all the 9 .class files are produced) :
java Payroll

Ok ... here are the 6 files needed in this Employee Payroll demo ...

Note that the names to give each file are in the top // comment line
as per the following 1st file: 

// Filename: Payroll.java //   //  version 2015-01-02 //


1.
Code: [Select]
// Payroll.java //  // 2015-01-02 //

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Payroll
{
    public static void main( String[] args ) throws IOException
    {
        Map < Integer, Employee > myMap = new HashMap <> ();

        do
        {
            Employee e = null;
            int id = 0;
            for( ; ; )
            {
                id  = TakeInEmployeeID.getID();
                if( !myMap.containsKey(id) ) // get rest of data ... //
                {
                    e = TakeInEmployeeData.getData();
                    e.setID( id );  // Ok ... now can set the unique ID ... //
                    break;
                }
                // else ...
                System.out.println( "ID " + id + " is already used ... "
                                + "So you DO NEED to re-enter, but with an UNIQUE ID ..." );
            }

            myMap.put( id, e ); // Ok ... got whole data set ... so can now add to container ... //

            double hours = 0.0;
            do
            {
                hours = TakeIn.takeInDbl( "Enter hours worked : " );
                if( hours < 0.0 || hours > 80.0 )
                    System.out.println( "Hours worked must be >= 0 and <= 80" );
            }
            while( hours < 0.0 || hours > 80.0 );

            System.out.print( e.getPayInfo() );
            System.out.format( " per hr x %.1f hrs = $%.2f%n%n", hours, hours * e.getPayRate() );
        }
        while( More.yn( 'y' ) ); // defaults to yes/more ... //


        System.out.println( "Your employee data so far is: " );  // Ok ... show all Employee records so far ... //
        for ( Integer key : myMap.keySet() )
            System.out.println( myMap.get(key) );
    }
}

class TakeInEmployeeID
{
    public static int getID() throws IOException
    {
        return TakeIn.takeInInt( "Enter id #         : " );
    }
}

class TakeInEmployeeData
{
    public static Employee getData() throws IOException
    {
        String fName = TakeInNonEmptyString.takeInStr( "Enter first name   : " );
        fName = ToCaps.toCapsOnFirstLetter( fName );

        String lName = TakeInNonEmptyString.takeInStr( "Enter last name    : " );
        lName = ToCaps.toAllCaps( lName );

        int dept = TakeIn.takeInInt( "Enter department # : " );

        double payRate = 0.0;
        do
        {
            payRate = TakeIn.takeInDbl( "Enter hourly rate  : " );
            if( payRate < 0.0 )
                System.out.println( "Pay rate must be >= 0" );
        }
        while( payRate < 0.0 );

        return new Employee( fName, lName, dept, payRate );
    }
}

class TakeInNonEmptyString
{
    public static String takeInStr( final String msg ) throws IOException
    {
        String s = null;
        for( ; ; )
        {
            s = TakeIn.takeInStr( msg ).trim();
            if( s.length() != 0 )
                break;
            // else
            System.out.println( "Blank lines are NOT valid input here ... " );
        }
        return s;
    }
}


2.
Code: [Select]
public class Employee extends Person
{
    private int id;
    private int dept;
    private double payRate;

    public Employee() {}

    public Employee( String firstName, String lastName )
    {
        super( firstName, lastName );
    }
    public Employee( String firstName, String lastName, int dept )
    {
        super( firstName, lastName );
        this.dept = dept;
    }
    public Employee( String firstName, String lastName, double payRate )
    {
        super( firstName, lastName );
        this.payRate = payRate;
    }

    public Employee( String firstName, String lastName, int dept, double payRate )
    {
        this( firstName, lastName, dept );
        this.payRate = payRate;
    }

    public Employee( String firstName, String lastName, int id, int dept, double payRate )
    {
        this( firstName, lastName, dept, payRate );
        this.id = id;
    }

    public void setID( int id )
    {
        this.id = id;
    }

    public int getID()
    {
        return id;
    }

    public double getPayRate()
    {
        return payRate;
    }

    public String getPayInfo()
    {
        return String.format( "ID(" + id + ") " + getFullName() + " is in dept# " + dept +
                                "%nwith pay rate of $%.2f", payRate );
    }
    @Override
    public String toString()
    {
        return String.format( "ID(" + id + ") " + getFullName() + " is in dept# " + dept
                                + " with pay rate of $%.2f", payRate ) + " per hour." ;
    }
}


3.
Code: [Select]
public class Person
{
    private String firstName;
    private String lastName;

    public Person() {}

    public Person( String firstName, String lastName )
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setFirstName( String firstName ) { this.firstName = firstName; }
    public void setLastName( String lastName ) { this.lastName = lastName; }

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public String getFullName() { return lastName + ", " + firstName; }
}
« Last Edit: January 18, 2015, 09:58:28 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
And the final 3 files needed (of the 6 needed) in the above Java Payroll demo program are available at this link:
(The files are to be named: TakeIn.java, ToCaps.java and More.java)

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

Offline David

  • Hero Member
  • *****
  • Posts: 579
    • View Profile
Now let's look at an example of coding a 'generic' (single) LinkedList container in Java 8 ...


Firstly the main test program file ...

Code: [Select]
import java.io.IOException;

class Test_LinkedList
{
    public static void main( String[] args ) throws IOException
    {
        testLinkedListString();
        TakeIn.takeInChr( "Press 'Enter' to continue ... " );
       
        testLinkedListDouble();
        TakeIn.takeInChr( "Press 'Enter' to continue ... " );
       
        testLinkedListPerson(); 
        TakeIn.takeInChr( "Press 'Enter' to continue/exit ... " );
    }
   
    public static Person takeInPerson() throws IOException
    {
        Person p = new Person();
        for( ; ; )
        {
            p.setFirstName( ToCaps.toCapsOnAllFirstLetters( takeInNonEmptyLine( "Enter first name  : " )) );
            p.setLastName( ToCaps.toCapsOnAllFirstLetters( takeInNonEmptyLine(  "Enter last name   : " )) );
            p.setPhone(                                     takeInNonEmptyLine( "Enter phone       : " )  );
            System.out.println( "You entered: " + p );
           
            if( Character.toLowerCase( TakeIn.takeInChr( "Ok (y/n) ? " ) ) == 'y' ) break;
            //else ...
            System.out.println( "Ok ... aborted ... try again ... " );
        }
        return p;
    }
   
    public static String takeInNonEmptyLine( String msg ) throws IOException
    {
        String tmp = null;
        for( ; ; )
        {
            tmp = TakeIn.takeInStr( msg ).trim();
            if( tmp.length() != 0 ) break;
            System.out.println( "\nEmpty lines are NOT valid input here ... \n" );
        }
        return tmp;
    }
   
    public static void testLinkedListString() throws IOException
    {
        String[] ary = { "Bill", "Jane" };
        LinkedList< String > words = new LinkedList<>( ary );
        words.push_front( "Bob" );
        words.push_front( "Anne" );
       
        System.out.println( "words.print() ..." );
        words.print();
        System.out.println( "\nwords.size() = " + words.size() );
       
        LinkedList< String > words2 = new LinkedList< String > (words);
        System.out.println( "words2.print() ..." );
        words2.print();
        System.out.println( "\nwords2.size() = " + words2.size() );
       
        System.out.println( "popping words ..." );
        String word = null;
        while( (word = words.pop_front()) != null )
        {
            System.out.println( word );
        }
        System.out.println( "AFTER ... popping words ..." );
        System.out.println( "words.print() ..." );
        words.print();
        System.out.println( "\nwords.size() = " + words.size() );
       
        System.out.println( "words2.print() ..." );
        words2.print();
        System.out.println( "\nwords2.size() = " + words2.size() );       

        words.push_back( "Bobby" );
        words.push_back( "Annie" );
        System.out.println( "AFTER adding 2 new ... words.print() ..." );
        words.print();
        System.out.println( "\nwords.size() = " + words.size() );
       
        words.clear();
        System.out.println( "AFTER words.clear() ... words.print() ..." );
        words.print();
        System.out.println( "\nwords.size() = " + words.size() ); 
    }
   
    public static void testLinkedListDouble() throws IOException
    {
        System.out.println();
       
        Double [] dAry = { 1d, 5.0, 4d, 3.0, 2d };
        LinkedList< Double > dLL  = new LinkedList<>( dAry  );
        System.out.println( "dLL.print() ..." );
        dLL.print();
        System.out.println( "\ndLL.size() = " + dLL.size() );

        System.out.println( "popping num's ..." );
        Double num = null;
        while( (num = dLL.pop_front()) != null )
        {
            System.out.println( num );
        }
        System.out.println( "AFTER ... popping num's ..." );
        System.out.println( "dLL.print() ..." );
        dLL.print();
        System.out.println( "\ndLL.size() = " + dLL.size() );
    }
   
    public static void testLinkedListPerson() throws IOException
    {
        System.out.println();
       
        LinkedList< Person > people = new LinkedList< Person > ();
        do
        {
            people.push_back( takeInPerson() );
        }
        while( More.yn() );
       
        System.out.println( "AFTER ... taking in people ..." );
        System.out.println( "people.print() ..." );
        people.print();
        System.out.println( "\npeople.size() = " + people.size() );
       
        System.out.println( "popping people ..." );
        Person pn = null;
        while( (pn = people.pop_front()) != null )
        {
            System.out.println( pn.toCustomString( p -> String.format( "Name: %-32s", p.getLastName() + ", " + p.getFirstName() )
                                                        + "  Phone: " + p.getPhone() ) );
        }
        System.out.println( "AFTER ... popping people ..." );
        System.out.println( "people.print() ..." );
        people.print();
        System.out.println( "\npeople.size() = " + people.size() );
    }
   
   
}


Then the class LinkedList file ...

Code: [Select]
public class LinkedList< T >
{
    // default ctor... creates an empty list ... //
    public LinkedList() {}
   
    // copy ctor ... //
    public LinkedList( final LinkedList< T > items )
    {
        if( items != null )
        {
            // Add the items to the list
            T tmp = items.front();
            while( tmp != null  )
            {
                push_back( tmp );
                tmp = items.next();
            }
         }
    }
   
    // ctor from an array of objects ... //
    public LinkedList( final T[] items )
    {
        if( items != null )
        {
            // Add the items to the list
            for( int i = 0; i < items.length; ++i )
            {
                push_back( items[i] );
            }
         }
    }
   
    public void push_front( T item )
    {
        ListItem newFront = new ListItem(item);
        if(front != null)
        {
            newFront.next = front;
            front = newFront;
        }
        else
        {
           front = back = newFront;
        }
        ++ length;
    }
   
     public void push_back( T item )
    {
        ListItem newBack = new ListItem(item);
        if( back != null )
        {
            back.next = newBack;
            back = newBack;
        }
        else
        {
           front = back = newBack;
        }
        ++ length;
    }
   
    public T front()
    {
        current = front;
        return front == null ? null : front.item;
    }
   
    public T next()
    {
        if( current != null )
        {
            current = current.next;
        }
        return current == null ? null : current.item;
    }
 
    public int size()
    {
        return length;
    }
   
    boolean empty()
    {
        return length == 0;
    }
   
    public T pop_front()
    {
        if( length > 1 )
        {
            T tmp = front();
            front = front.next;
            --length;
            return tmp;
        }
        // else ...
        if( length == 1 )
        {
            T tmp = front();
            front = back = null;
            --length;
            return tmp;
        }
        return null;
    }
   
    public void print()
    {
        T tmp = front();
        System.out.print( "[" );
        int count = 0;
        while( tmp != null )
        {
            if( ++count < length ) System.out.print( tmp +", " );
            else System.out.print( tmp );
            tmp = next();
        }
        System.out.print( "]" );
    }
 
    public void clear()
    {
        while( !empty() ) pop_front();
    }
   
    protected ListItem front   = null;
    protected ListItem back    = null;
    protected ListItem current = null;
    protected int length       = 0;
   
   
    protected class ListItem
    {
        // ctor...
        public ListItem( T item )
        {
            this.item = item;
            next = null;
        }
        T item;
        ListItem next;
    }
}


Then the class Person file ...

Code: [Select]
import java.util.function.Function;

/**
 * @author dw
 */
public class Person
{
    private String firstName;
    private String lastName;
    private String phone;
 
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
    public void setPhone(String val)
    {
        phone = val;
    }

   
    public String getFirstName()
    {
        return firstName;
    }
    public String getLastName()
    {
        return lastName;
    }
     public String getPhone()
    {
        return phone;
    }

    public String toCustomString( Function < Person, String > f )
    {
        return f.apply(this);
    }
   
    @Override
    public String toString()
    {
        return firstName + " " + lastName + " " + phone;
    }     
}

The other 3, of the 6 files needed here are available here ...

The files are:  "More.java", "ToCaps.java" and "TakeIn.java"

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

« Last Edit: October 02, 2016, 04:58:27 PM by David »