// 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;
}
}
// 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;
}
}
// 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;
}
}
// 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' );
}
}
@echo off
rem path
javac TestTakeIn.java
dir *.class
pause
java TestTakeIn
pause
// 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' ... //
}
}
@echo off
javac TestReadWholeFile.java
dir *.class
pause
java TestReadWholeFile
pause
// 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) ) );
}
}
// 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 );
}
}
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" );
}
}
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 );
}
}
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) );
}
}
}
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;
}
}
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
//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() );
}
}
}
//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 );
}
}
//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 );
}
}
# 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 ... " )
# 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 ... " )
/* 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();
}
/* 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;
}
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();
}
}
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 );
}
}
// 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;
}
}
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." ;
}
}
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; }
}
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() );
}
}
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;
}
}
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;
}
}