Author Topic: Six Fast Steps in Java 8 ... (a continuation of the Six Fast Steps series)  (Read 21606 times)

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Here is a new "Six Fast Steps in Java 8" series of demo programs to fast-track new Java programmers.


Update!  FREE homework help NOW available via e-mail ... (or in person if in Toronto Ontario Canada region.)

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



The first part consists of a series of 5 example programs that students may like to have for reference and to use as a working 'shell' from which to start a project.

1. The first program is just a most basic 'shell' that compiles, and when run, asks the user to press 'More' (y/n) ? to loop again or quit.

2. The next program illustrates getting a sum and finding the average of valid numeric input in a loop.

3. The next three programs progress from inputting numbers into an ARRAY that has the max size fixed at compile time ... to using an ArrayList ... and then a LinkedList container to hold as many numbers as the user wishes (limited only by available memory). They also illustrate how to SORT, FIND, or ERASE elements from the respective containers.

(All the numeric input examples above find the sum and average value of the numbers input.)

Then the 6th program features using a Java class ... class BP (Blood Pressure) 


But firstly, a little 'TakeInLine' class ...

to facilitate prompting for ...

and inputting (whole lines) from the keyboard ...

to obtain valid and crash-proof ...

Java int, long and double, etc... data types.


Code: [Select]
/**
 * @version: 2017-11-27
 * @author: dwz
 * See file: TakeInLineTest.java for demo of how to use. //
 */

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


public class TakeInLine {
    // Create a BufferedReader using System.in ... //
    private BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
   
    private static String errFormatStr = "Please enter a VALID '%s' number.%n";
   
    public String takeInLine( String msg ) {
        System.out.print( msg );
        String line = null;
        try {
            line = br.readLine();
        } catch( IOException e ) {
            System.err.println( e );
            System.out.println( "UNEXPECTED string input error." );
            line = ""; // default here to empty line ... //
        }
        return line;
    }
 
 
    public char takeInChar( String msg ) {   
        String line = takeInLine( msg );
        if( line.length() > 0 ) {
            return (char)line.charAt(0);
        } else {
            return (char)0;
        }
    }


    public int takeInInt( String msg ) {   
        while( true )
        {
            try {
                return Integer.parseInt( takeInLine( msg ) );
            } catch( NumberFormatException e ) {
                System.out.format( errFormatStr, "int"  );
            };
        }
    }
   

    public long takeInLong( String msg ) {   
        while( true ) {
            try {
                return Long.parseLong( takeInLine( msg ) );
            } catch( NumberFormatException e ) {
                System.out.format( errFormatStr, "long" );
            }
        }
    }
   
   
    public double takeInDouble( String msg ) {   
        while( true ) {
            try {
                return Double.parseDouble( takeInLine( msg ) );
            } catch( NumberFormatException e ) {
                System.out.format( errFormatStr, "double"  );
            }
        }
    }
   



    // call as more('y') if yes is to be the default case ...
    // call as more('n') if no is to be the default case //

    public boolean more( final char defaultChar ) { // 'y' or 'n' tells 'defaultChar' ... //

        char reply = Character.toLowerCase( takeInChar( "More (y/n) ? " ) );
       
        if( defaultChar == 'y' ) {
            return reply != 'n';
        } else {
            return reply == 'y';
        }
    }

    // this defaults to case: "yes more"
    // unless 'n' or 'N' is entered as first char on line //
    public boolean more() {
        return more( 'y' );
    }
}


And a little test program ...

Code: [Select]
/**
 * @version: 2017-11-21
 * @author: dwz
 *
 * Short demo of using my custom class TakeInLine
 */

class TakeInLineTest {

    private static TakeInLine til = new TakeInLine();
   
    public static void main( String[] args ) {
        int pin = 0;
        long id = 0L;
        for( ; ; ) {
            String name   = til.takeInLine(   "Enter this user name :  " );
            for( ; ; ) {
                pin       = til.takeInInt(    "Enter pin (8 digits) :  " );
                if( validNumDigits( pin, 8 ) ) break;
                System.out.println( "Need 8 digits to continue ..." );
            }
            for( ; ; ) {
                id       = til.takeInLong(    "Enter ID (16 digits) :  " );
                if( validNumDigits( id, 16 ) ) break;
                System.out.println( "Need 16 digits to continue ..." );
            }
            double amount = til.takeInDouble( "Enter $ amount owing :  " );
            System.out.println();

            System.out.format( "%s, %d, %d owes: %,1.2f dollars. %n", name, pin, id, amount );
            System.out.println();
            System.out.println( "On to next client?" );
            System.out.print( "Whenever you are ready, enter y or n, " );
            System.out.println( "or just press the Enter key for 'y'." );
           
            if( !til.more() ) break;
        }
    }
   
    static boolean validNumDigits( long num, int numDig ) {
        String valStr = "" + num;
        return valStr.length() == numDig;
    }
}


Now the first program in this series ... it just loops and prompts the user asking More (y/n)?

(1.)
Code: [Select]
// 2016-09-29 //


// uses my custom class TakeInLine  //


class DoWhileMore {

    public static void main( String[] args ) {

        // create a new TakeInLine object called til //
        TakeInLine til = new TakeInLine();

        do {

            // Your code goes here //

        } while( til.takeInChar( "More (y/n) ? " ) != 'n' );
    }
}


Now the 2nd program in this series ...

(2.)
Code: [Select]
// 2017-11-21 //

// uses my custom class TakeInLine  //


class MoreInts {
   
    public static void main( String[] args ) {

        // loop repeatedly while more() returns true ...
        // Note that the default return value of more()
        // if nothing entered (and just pressed return) is true //
       
        long sum = 0;
        int count = 0;
        // create a new TakeInLine object called til //
        TakeInLine til = new TakeInLine();
        do {
            // call my method takeInInt and pass in the required prompt String //
            int num = til.takeInInt( "Enter an 'int' number: " );
            ++ count;
            // update the sum
            sum += num;
        } while( til.more() );

        System.out.println( "The sum of the " + count
                            + " numbers is: " + sum );
        System.out.println( "The avg of the " + count
                            + " numbers is: " + (double)sum/count );
    }
}

P.S.

You might like to look at the next link to see an other very simple,
and beginning student inspired,
Java class to handle Console IO:

https://www.daniweb.com/programming/software-development/threads/506147/developing-a-class-to-ease-student-coding-crash-proof-and-valid-io
« Last Edit: November 28, 2017, 05:50:12 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
An array of type int

(3.a )
Code: [Select]
// 2016-11-16 //


// uses my custom class TakeInLine
// enters integer data, finds sum, average, sorts, finds value, erase, show ... //


import java.util.Arrays;


class ArrayInt {
    final static int MAX_SIZE = 5; // use a small size here to ease testing //   
 
    public static void main( String[] args ) {

        int[] myAry = new int[ MAX_SIZE ]; // create to hold up to MAX_SIZE int's //
        int size = 0;
       
        TakeInLine til = new TakeInLine();

        do {
            myAry[ size ] = til.takeInInt( "Enter next integer to sum: " );
            ++ size;
            if( size == MAX_SIZE ) {
                System.out.println( "You have reached the maximum "
                                    + MAX_SIZE + " number of elements." );
                break;
            }
        } while( til.more() );
       
        double sum = sumAry( myAry, size );
       
        System.out.println( "\nFor " + size+ " numbers entered, sum is "
                            + sum + " and array average is " + sum/size );
             
        System.out.print( "\nshowAry: " );
        showAry( myAry, size );
       

        int last = myAry[ size-1 ]; // size is always at least 1 //

        Arrays.sort( myAry, 0, size );
        reverse( myAry, size );
     

        System.out.print( "\nAfter sorting and reversing ...\nshowAry: " );
        showAry( myAry, size );
   
        int i = findIndex( myAry, size, last );
        if( i != -1 ) {
            size = eraseIndex( myAry, size, i );

            System.out.println( "\nAfter erasing " + last + " ..." );
            System.out.println( "\nshowAry: " );
            showAry( myAry, size );
        } else {
            System.out.println( last + " NOT found in array." );
        }           
    }


    static double sumAry( final int[] ary, final int size ) {
        double sum = 0.0;
        for( int i = 0; i < size; ++ i ) {
            sum += ary[i];
        }
        return sum;
    }

    static void showAry( final int[] ary, final int size ) {
        for( int i = 0; i < size; ++ i ) {
            System.out.print( ary[i] + " " );
        }
        System.out.println();
    }


    static int findIndex( final int[] ary, final int size, final int value ) {
        for( int i = 0; i < size; ++i ) {
            if( ary[i] == value )
                return i;
        }
        // else if reach here ...
        return -1;
    }

    static int eraseIndex( int[] ary, final int size,
                           final int index ) {
        for( int i = index; i < size-1; ++i ) {
            ary[i] = ary[i+1]; // copy each element above, down one index, so erased
        }
        return size-1;
    }

    static void reverse( int[] ary, final int size ) {
        int tmp;
        for( int i = 0, end = size - 1; i < end; ++i, --end ) {
            tmp = ary[i];
            ary[i] = ary[end];
            ary[end] = tmp;
        }
    }
}


(3.b)  <-- a variant of (3.a)
Code: [Select]
// 2016-11-16 //


// uses my custom class TakeInLine
// enters integer data, finds sum, average, sorts, finds value, erase, show ... //


import java.util.Arrays;
import java.util.stream.IntStream;



class ArrayInt2 {
    final static int MAX_SIZE = 5; // use a small size here to ease testing //   
 
    public static void main( String[] args ) {

        int[] myAry = new int[ MAX_SIZE ]; // create ALL zero, to hold up to MAX_SIZE int's //
        int size = 0;
       
        TakeInLine til = new TakeInLine();

        do {
            myAry[ size ] = til.takeInInt( "Enter next integer to sum: " );
            ++ size;
            if( size == MAX_SIZE ) {
                System.out.println( "You have reached the maximum "
                                    + MAX_SIZE + " number of elements." );
                break;
            }
        } while( til.more() );
       
        //double sum = sumAry( myAry, size );
        //double sum = IntStream.of( myAry ).sum();
        double sum = IntStream.of( myAry ).parallel().sum(); // NOTE! Any unused elements were initialed to 0 value //
       
        System.out.println( "\nFor " + size+ " numbers entered, sum is "
                            + sum + " and array average is " + sum/size );
             
        System.out.print( "\nshowAry: " );
        showAry( myAry, size );
       

        int last = myAry[ size-1 ]; // size is always at least 1 //

        Arrays.sort( myAry, 0, size );
     

        System.out.print( "\nAfter sorting  ...\nshowAry: " );
        showAry( myAry, size );
   
        //int i = findIndex( myAry, size, last );
        int i = Arrays.binarySearch( myAry, 0, size, last );

        if( i != -1 ) {
            size = eraseIndex( myAry, size, i );

            System.out.print( "\nAfter erasing " + last + " and reversing ... " );
            reverse( myAry, size );
            System.out.println( "\nshowAry: " );
            showAry( myAry, size );
        } else {
            System.out.println( last + " NOT found in array." );
        }           
    }

/*
    static double sumAry( final int[] ary, final int size ) {
        double sum = 0.0;
        for( int i = 0; i < size; ++ i ) {
            sum += ary[i];
        }
        return sum;
    }
*/
    static void showAry( final int[] ary, final int size ) {
        for( int i = 0; i < size; ++ i ) {
            System.out.print( ary[i] + " " );
        }
        System.out.println();
    }

/*
    static int findIndex( final int[] ary, final int size, final int value ) {
        for( int i = 0; i < size; ++i ) {
            if( ary[i] == value )
                return i;
        }
        // else if reach here ...
        return -1;
    }
*/
    static int eraseIndex( int[] ary, final int size,  final int index ) {
        for( int i = index; i < size-1; ++i ) {
            ary[i] = ary[i+1]; // copy each element above, down one index, so erased
        }
        return size-1;
    }

    static void reverse( int[] ary, final int size ) {
        int tmp;
        for( int i = 0, end = size - 1; i < end; ++i, --end ) {
            tmp = ary[i];
            ary[i] = ary[end];
            ary[end] = tmp;
        }
    }
}


And also, an array of Java type Integer

(3.c)
Code: [Select]
/// 2016-11-16 //


// uses my custom class TakeInLine
// enters integer data, finds sum, average, sorts, finds value, erase, show ... //


import java.util.Arrays;
import java.util.Comparator;



class ArrayInteger
{
    final static int MAX_SIZE = 5; // use a small size here to ease testing //   
 
    public static void main( String[] args ) {

        // create to hold up to MAX_SIZE int's //
        Integer[] myAry = new Integer[ MAX_SIZE ];

        int size = 0; // index of next postion available to fill //
       
        TakeInLine til = new TakeInLine();

        do {
            myAry[ size ] = til.takeInInt( "Enter next integer to sum: " );
            ++ size;
            if( size == MAX_SIZE ) {
                System.out.println( "You have reached the maximum "
                                    + MAX_SIZE + " number of elements." );
                break;
            }
        } while( til.more() );
       
        double sum = sumAry( myAry, size );;
       
        System.out.println( "\nFor " + size+ " numbers entered, sum is "
                            + sum + " and array average is " + sum/size );
             
        System.out.print( "\nshowAry: " );
        showAry( myAry, size );
       

        Integer last = myAry[ size-1 ]; // size is always at least 1 //

        Arrays.sort( myAry, 0, size );

        System.out.print( "\nAfter sorting ...\nshowAry: " );
        showAry( myAry, size );
   
        //int i = findIndex( myAry, size, last );
        int i = Arrays.binarySearch( myAry, 0, size, last );
        if( i != -1 ) {
            size = eraseIndex( myAry, size, i );

            System.out.println( "\nAfter erasing " + last + " ..." );

            Arrays.sort( myAry, 0, size, new ReverseIntegers() );

            System.out.print( "\nAfter sorting in reversed order ...\nshowAry: " );
            showAry( myAry, size );
        } else {
            System.out.println( last + " NOT found in array." );
        }           
    }


    static double sumAry( final Integer[] ary, final int size ) {
        double sum = 0.0;
        for( int i = 0; i < size; ++ i ) {
            sum += ary[i];
        }
        return sum;
    }

    static void showAry( final Integer[] ary, final int size ) {
        for( int i = 0; i < size; ++ i ) {
            System.out.print( ary[i] + " " );
        }
        System.out.println();
    }

/*
    static int findIndex( final Integer[] ary, final int size,
                          final Integer value ) {
        for( int i = 0; i < size; ++i ) {
            if( value == ary[i] ) {
                return i;
            }
        }
        // else if reach here ...
        return -1;       
    }
*/
    static int eraseIndex( Integer[] ary, final int size, final int index ) {
        for( int i = index; i < size-1; ++i ) {
            ary[i] = ary[i+1]; // copy each element above, down one index, so erased
        }
        return size-1;
    }
}


class ReverseIntegers implements Comparator < Integer > {
    public int compare( Integer a, Integer b ) {
        return b.compareTo(a);
    }
}


« Last Edit: November 17, 2016, 02:22:40 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Java class ArrayListInt


(4.)
Code: [Select]
// 2016-09-29 //


// uses my custom class TakeInLine
// enters integer data, finds sum, average, sorts, finds value, erase, show ... //


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


class ArrayListInt {

    public static void main( String[] args ) {

        // get a new TaKeInLine obj.
        TakeInLine til = new TakeInLine();

        // get a new (empty) ArrayList to hold Integers
        List < Integer > my_lst = new ArrayList<>();

        do {
            // prompt and takeIn next int that gets converts to Integer when append to List
            int tmpInt = til.takeInInt( "Enter next integer to sum: " );
            my_lst.add(tmpInt);

        } while( til.more() );
       
        double sum = sumLst( my_lst );
       
        System.out.format( "%nFor %d numbers entered, sum is: %1.2f", my_lst.size(), sum );
        System.out.format( "%nArrayList average is: %1.2f%n", sum/my_lst.size() );
             
        System.out.println( "my_lst: " + my_lst );
       

        int last = my_lst.get(my_lst.size()-1);

        Collections.sort( my_lst, (a, b) -> -a.compareTo(b) );

        System.out.println( "\nAfter sorting descending ...\nmy_lst: " + my_lst );

   
        int i = my_lst.indexOf( last );

        if( i != -1 ) {
            my_lst.remove( i );

            System.out.println( "\nAfter erasing " + last + " ..." );
            System.out.println( "my_lst: " + my_lst );
        } else {
            System.out.println( last + " NOT found in lst." );
        }
    }


    static double sumLst( final List< Integer > lst ) {
        double sum = 0.0;
        for( int val : lst ) {
            sum += val;
        }
        return sum;
    }
}


Java class LinkedListInt

(5.)
Code: [Select]
// 2016-09-29 //


// uses my custom class TakeInLine
// enters integer data, finds sum, average, sorts, finds value, erase, show ... //



import java.util.List;
import java.util.LinkedList;
import java.util.Collections;


class LinkedListInt {

    public static void main( String[] args ) {

        // get a new TaKeInLine obj.
        TakeInLine til = new TakeInLine();

        // get a new (empty) List to hold Integers
        List < Integer > my_lst = new LinkedList<>();

        do {
            // prompt and takeIn next int that gets converts to Integer when append to List
            int tmpInt = til.takeInInt( "Enter next integer to sum: " );
            my_lst.add(tmpInt);

        } while( til.more() );
       
        double sum = sumLst( my_lst );
       
        System.out.format( "%nFor %d numbers entered, sum is: %1.2f", my_lst.size(), sum );
        System.out.format( "%nArrayList average is: %1.2f%n", sum/my_lst.size() );
             
        System.out.println( "my_lst: " + my_lst );
       

        int last = my_lst.get(my_lst.size()-1);

        Collections.sort( my_lst, (a, b) -> -a.compareTo(b) );

        System.out.println( "\nAfter sorting descending ...\nmy_lst: " + my_lst );
       
       
        //int i = my_lst.indexOf( last );

        // MUST pass in Integer object here, to use call to lst.remove(obj) //
        if( /*i != -1*/ my_lst.remove( new Integer(last) ) ) {
            //my_lst.remove( i ); // call here is to lst_remove( intIndex ) //

            System.out.println( "\nAfter remove of " + last + " ..." );
            System.out.println( "my_lst: " + my_lst );
        } else {
            System.out.println( last + " NOT found in lst." );
        }       
    }


    static double sumLst( final List< Integer > lst ) {
        double sum = 0.0;
        for( int val : lst ) {
            sum += val;
        }
        return sum;
    }
}
« Last Edit: October 04, 2016, 12:49:51 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
This 6th step features reading and writing (text) data files,

using Java's latest nio - file New IO ...
 

(6.)
Code: [Select]
/**
 * @version: 2017-12-04
 * @author: dwz
 * This demo uses the latest Java 'new file io' (nio) ...
 * to read a .txt data file of names and blood pressures
 * and then to print a possible diagnosis to console and file.
 */


// structure of data file: BP.txt //
/*
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;


class BloodPressure {
   
    final static String FNAME = "BP.txt";
    final static String RESULTS_FNAME = "Results" + FNAME;

    public static void main( String[] args ) {
       
        if( Files.exists( Paths.get( FNAME ) ) ) {
            try( BufferedReader fin = Files.newBufferedReader( Paths.get( FNAME ) ); // note ; here //
               
                    BufferedWriter fout = Files.newBufferedWriter( Paths.get( RESULTS_FNAME ),
                            Charset.defaultCharset() ) ) {
                 
                BP bp  = new BP();
                String line = null;
             
                // read lines until EOF is reached, i.e. here ... until null is returned //
                while( ( line = fin.readLine() ) != null ) {
                    String[] lst = line.split( "[/ ]" );
                    //System.out.println( "lst.length = " + lst.length ); //debugging//
                    bp.lname = lst[0];
                    bp.fname = lst[1];
                    try {
                        bp.sys = Integer.parseInt( lst[2] );
                        bp.dia = Integer.parseInt( lst[3] );
                       
                    } catch( NumberFormatException ex ) {
                        System.out.println( ex );
                    }
                   
                    String text = bp.toString();
                    System.out.println(text); // write to console screen ...

                    //fout.write( text, 0, text.length() );
                    fout.write( text ); // write to RESULT file //
                    fout.newLine(); // Write separator //
                }

            }
            catch( IOException ex) {
                System.out.println( ex );
            }
        } else {
            System.out.println( "There was a problem finding file: " + FNAME );
        }
    }
}


class BP { // class BP handles data and methods called for Blood Pressure Objects //

    final static String UNKNOWN = " <--\n Unrecognized diagnosis. \n" +
        "* CHECK VALIDITY of DATA entered. *";
    String lname, fname;
    int sys, dia;
       
    String getDiagnosis() { // Note: need since returning as part of toString //

        if( sys < 120/2 || dia < 80/2 ) // ?? //
            return UNKNOWN;
        if( sys > 120*2 || dia > 80*2 ) // ?? //
            return UNKNOWN;

        if( sys >= 160 || dia > 100 )
            return " <--\n CHECK AGE re. possible Stage 2 Hypertension.";
        if( sys >= 140 || dia >= 90 )
            return " <--\n CHECK AGE re. possible Stage 1 Hypertension.";
        if( sys >= 120 || dia >= 80 )
            return " <--\n CHECK AGE re. possible Pre-Hypertension.";
        // else ...
        return "\n Normal";
    }
   
    @Override
    public String toString() { // Note that this toString method also calls the getDiagnosis method //
        // print left adujust string in 40 spaces, right adjusts each number in 3 spaces
        // then print
        return String.format( "%-40s %3d/%3d %s", (lname + ", " + fname),
            sys, dia, getDiagnosis() );
    }
}
« Last Edit: December 06, 2017, 05:07:07 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Six Fast Steps in Java 8 ... (a continuation of the Six Fast Steps series)
« Reply #4 on: November 21, 2017, 05:51:46 AM »
(6. version 2)  New file stream version - uses file: class BP below


Code: [Select]
/**
 * @version: 2017-12-05
 * @author: dwz
 * This demos using the latest Java 8 Stream, with map and ForEach methods,
 * to read a .txt data file of names and blood pressures
 * and then to print a possible diagnosis to console and file.
 * (Note that each result (String) gets stored in a List <String> container here.)
 */
 

// structure of data file: BP.txt //
/*
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


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

import java.io.IOException;

import java.util.stream.Stream;
import java.util.List;
import java.util.ArrayList;


public class BloodPressure2 {

    final static String FNAME = "BP.txt";
    final static String RESULTS_FNAME = "Results" + FNAME;
    // get (a ref to) an empty List to be filled up below //
    final static List< String > results = new ArrayList<> ();

    public static void main( String[] args ) {
           
        try( Stream< String > lines = Files.lines( Paths.get( FNAME ) ) ) {
            lines.map( line -> diagnoseAndAddResultString(line) )
                 .forEach( System.out::println );
       
        } catch( IOException ex ) {
            System.out.println( ex );
        }
       
        // ok ... now can write List of results to file ...
        try {
            Files.write( Paths.get( RESULTS_FNAME ), results, Charset.defaultCharset() );
        } catch( IOException ex ) {
            System.out.println( ex );
        }
    }
   
    static String diagnoseAndAddResultString( String line ) {
        BP bp = new BP( line );
        String tmp = bp.toString(); // tmp now holds diagnosis also //
        results.add( tmp ); // Note that results is a (ref. to a) List< String > object //
        return tmp;
    }
}


And here is the class BP used above ...

Code: [Select]
/**
 * @version: 2017-12-05
 * @author: dwz
 * class BP handles Blood Pressure data
 * and methods to get and show a diagnosis
 */


// structure of data file ...
// BP.txt //
/*
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


public class BP {

    private final static String UNKNOWN = " <--\n Unrecognized diagnosis. \n" +
        "* CHECK VALIDITY of DATA entered. *";
    private String lname, fname;
    private int sys, dia;
   
    // ctor from passed in String line of data (from file) //
    public BP( String line ) {
        String[] ary = line.split( "[/ ]" ); // split on char '/' or char ' ' //
        //System.out.println( "ary.length = " + ary.length ); //debugging//
        lname = ary[0];
        fname = ary[1];
        try {
            sys = Integer.parseInt( ary[2] );
            dia = Integer.parseInt( ary[3] );
           
        } catch( NumberFormatException ex ) {
            System.out.println( ex );
        }
    }
       
    // Note: this returned string is also returned as part of below toString() //
    public String getDiagnosis() {

        if( sys < 120/2 || dia < 80/2 ) // ?? //
            return UNKNOWN;
        if( sys > 120*2 || dia > 80*2 ) // ?? //
            return UNKNOWN;

        if( sys >= 160 || dia > 100 )
            return " <--\n CHECK AGE re. possible Stage 2 Hypertension.";
        if( sys >= 140 || dia >= 90 )
            return " <--\n CHECK AGE re. possible Stage 1 Hypertension.";
        if( sys >= 120 || dia >= 80 )
            return " <--\n CHECK AGE re. possible Pre-Hypertension.";
        // else ...
        return "\n Normal";
    }
   
    // Note that this method calls above method getDiagnosis() //
    @Override
    public String toString() {
        // left adjust string of combined lname + ", " + fname in 40 spaces,
        // right adjust each number in 3 spaces
        return String.format( "%-40s %3d/%3d %s", (lname + ", " + fname),
            sys, dia, getDiagnosis() );
    }
}


And a demo text data file:  BP.txt

Code: [Select]
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111


And another Java 8 way ...
6. (version 2a)

Code: [Select]
/**
 * @version: 2017-12-05
 * @author: dwz
 * This demos using the latest Java 8 Stream with map, filter and collect methods ...
 * to read a .txt data file of names and blood pressures
 * and then to print a possible diagnosis to console and file
 * for all NOT Normal results ... sorted by names (Note result String starts with lname, fname).
 */
 

// structure of data file: BP.txt //
/*
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


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

import java.io.IOException;

import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.List;
//import java.util.Collections;


public class BloodPressure2a {

    final static String FNAME = "BP.txt";
    final static String RESULTS_FNAME = "Results" + FNAME;


    public static void main( String[] args ) {

        List< String > results = null;
           
        try( Stream< String > lines = Files.lines( Paths.get( FNAME ) ) ) {
            // filter out all Normal results //
            results = lines.map( line -> (new BP( line )).toString() )
                           .filter( diaText -> ! diaText.substring(diaText.length()-6).equals("Normal") )
                           .sorted()
                           .collect( Collectors.toList() );
       
        } catch( IOException ex ) {
            System.out.println( ex );
        }


        // Now can sort result strings by names (that appear at front of each result string) //
        //Collections.sort( results );


        //for( String result : results ) // Now can print list of (NOT Normal) results to Console //
            //System.out.println( result );
        // or //
        results.stream().forEach( System.out::println );

        try { // And now can write List of results to file //
                       
            Files.write( Paths.get( RESULTS_FNAME ), results, Charset.defaultCharset() );
        } catch( IOException ex ) {
            System.out.println( ex );
        }
    }
}
« Last Edit: December 06, 2017, 05:10:08 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Six Fast Steps in Java 8 ... (a continuation of the Six Fast Steps series)
« Reply #5 on: November 28, 2017, 04:29:38 AM »
6. (version 3 - no Java List container is used here)

Code: [Select]
/**
 * @version: 2017-12-05
 * @author: dwz
 * This demo uses the latest Java 8 Stream with map, filter and forEach methods
 * to read a .txt data file of names and blood pressures
 * and then to print a possible diagnosis to console and file
 * for each (NOT Normal) file record as read and processed.
 * (i.e. NO storage container is used here.)
 */
 

// structure of data file: BP.txt //
/*
Smith Jane 133/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


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

import java.io.IOException;
import java.io.BufferedWriter;

import java.util.stream.Stream;


public class BloodPressure3 {

    final static String FNAME = "BP.txt";
    final static String RESULTS_FNAME = "Results" + FNAME;

    public static void main( String[] args ) {
           
        try( Stream< String > lines = Files.lines( Paths.get( FNAME ) );

            BufferedWriter bw = Files.newBufferedWriter( Paths.get( RESULTS_FNAME ),
                    Charset.defaultCharset() ) ) {
                   
            lines.map( line -> (new BP(line)).toString() )
                 .filter( diaText -> ! diaText.substring( diaText.length() - 6 ).equals( "Normal" ) )
                 .forEach( diaText -> output( diaText, bw ) );
                 
        } catch( IOException ex ) {
            System.out.println( ex );
        }
    }
   
    static void output( String diaText, BufferedWriter bw ) {
        System.out.println( diaText ); // print result to Console //
        try {
            bw.write( diaText ); // bw.write( diaText, 0, diaText.length() );
            bw.newLine();   
        } catch( IOException ex ) {
            System.out.println( ex );
        }
    }
}
« Last Edit: December 06, 2017, 05:11:40 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Six Fast Steps in Java 8 ... (a continuation of the Six Fast Steps series)
« Reply #6 on: November 28, 2017, 04:37:17 AM »
A simple Java reading-file-lines example vs a Java 8 version ...

Code: [Select]
/**
 * @version 2017-11-26
 * @author dwz
 * An example of a simple way a beginning student might code
 * to read a text file line by line ... displaying each line as read.
 */


import java.util.Scanner;
import java.nio.file.Paths;
import java.io.IOException;


class ScanFileTest {
   
    // Place this file in the same folder
    // as the .class file(s) produced here. //
    static String FNAME = "Persons.txt";
   
    public static void main( String[] args ) {
       
        // code for try with resources that are auto-closeable //
        try( Scanner scan = new Scanner( Paths.get( FNAME ) ) ) {
            String line = null;
            while( scan.hasNext() ) {
                line = scan.nextLine();
                System.out.println( line );
            }
        } catch( IOException ex ) {
            System.out.println( ex );
        }       
    }
}

Also ...

Code: [Select]
/**
 * @version 2017-12-05
 * @author dwz
 * An example of a simple way a beginning student might code
 * to read a (small) text file into an ArrayList < Person > ...
 * then to display that List < Person > in some sorted order
 * specified by using a lambda function to control the sort.
 */

// structure of below used data file: Persons.txt //
/*
Matt 1 19820611
Bonnie 2 19830202
Theo 3 20140712
Isla 4 20171119
*/


import java.util.Scanner;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;


class ScanFileTest2 {
   
    // Place this file in the same folder
    // as the .class file(s) produced here. //
    static String FNAME = "Persons.txt";
   
    public static void main( String[] args ) {
        List < Person > mattsFamily = new ArrayList <> (); // get an empty ArrayList //
       
        // code for try with resources that are auto-closeable //
        try( Scanner scan = new Scanner( Paths.get( FNAME ) ) ) {
            String line = null;
            while( scan.hasNext() ) {
                line = scan.nextLine();
                mattsFamily.add( new Person( line ) );
            }
        } catch( IOException ex ) {
            System.out.println( ex );
        }

        // show all family ... but firstly sort list by birthdays, youngest first //
        Collections.sort( mattsFamily, (a, b) -> b.dob.compareTo(a.dob) );
        for( Person per : mattsFamily ) {
            System.out.println( per ); // calls toString method here //
        }       
    }
}


// an example of a simple class Person //
class Person {
    protected String name, id, dob;
   
    // constructor from (here a file) line passed in //
    public Person( String line ) {

        String[] ary = line.split(" ");
        name = ary[0];
        id = ary[1];
        dob = ary[2];
    }
   
    @Override
    public String toString() {
        return name + ", id: " + id + ", dob: " + dob;
    }
}
« Last Edit: December 06, 2017, 05:14:22 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Six Fast Steps in Java 8 ... (a continuation of the Six Fast Steps series)
« Reply #7 on: November 28, 2017, 04:40:05 AM »
Java 8 Stream versions ...

Code: [Select]
/**
 * @version 2017-11-27
 * @author dwz
 * An example of a Java 8 way a student might code to read
 * a text file line into a Stream ... displaying each line as read.
 */

// structure of below used data file: Persons.txt //
/*
Matt 1 19820611
Bonnie 2 19830202
Theo 3 20140712
Isla 4 20171119
*/


import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.util.stream.Stream;


class StreamFileTest {
   
    // Place this file in the same folder
    // as the .class file(s) produced here. //
    static String FNAME = "Persons.txt";
   
    public static void main( String[] args ) {
       
        // code for try with resources that are auto-closeable //
        try( Stream< String > myLines = Files.lines( Paths.get( FNAME ) ) ) {
            myLines.forEach( System.out::println );
        } catch( IOException ex ) {
            System.out.println( ex );
        }       
    }
}

Also ...

Code: [Select]
/**
 * @version 2017-12-05
 * @author dwz
 * An example of a Java 8 way a student might code to read
 * text file lines into a Stream < String > ...
 * parsing each line (in the stream) into a Person object ...
 * and adding that new Person object to a growing List of type Person,
 * then show that list sorted by names.
 */


// structure of below used data file: Persons.txt //
/*
Matt 1 19820611
Bonnie 2 19830202
Theo 3 20140712
Isla 4 20171119
*/


import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;


class StreamFileTest2 {
   
    // Place this file in the same folder
    // as the .class file(s) produced here. //
    static String FNAME = "Persons.txt";
   
    public static void main( String[] args ) {
   
        List < Person > mattsFamily = new ArrayList <> ();
       
        // code for try with resources that are auto-closeable //
        try( Stream< String > myLines = Files.lines( Paths.get( FNAME ) ) ) {
            // note use below of lambda function: line -> mattsFamily.add( new Person(line) //
            myLines.forEach( line -> mattsFamily.add( new Person(line) ) );
        } catch( IOException ex ) {
            System.out.println( ex );
        }

        Collections.sort( mattsFamily, (a, b) -> a.name.compareTo(b.name) );
        // Now show each Person in the sorted List < Person> object: mattsFamily ...
        for( Person per : mattsFamily ) {
            System.out.println( per ); // calls the 'toString' Person method //
        }
    }
}


// an example of a simple class Person //
class Person {
    String name, id, dob;
   
    // constructor from (here a file) line passed in //
    public Person( String line ) {

        String[] ary = line.split(" ");
        name = ary[0];
        id = ary[1];
        dob = ary[2];
    }
   
    @Override
    public String toString() {
        return name + ", id: " + id + ", dob: " + dob;
    }
}
« Last Edit: December 06, 2017, 05:16:11 AM by David »