CS670K - Special Topics - Java for C++ Programmers - Fall 1997
© Copyright 1997 University of New Haven
A program to copy a byte at a time from the input stream to the output print stream:
import java.io.*;
class copy1
{
public static void main(String s[]) throws IOException
{
int c;
for (c= System.in.read(); c>=0; c= System.in.read()) System.out.write(c);
}
}
A program to copy bytes, a line at a time from the input stream to the output print stream:
import java.io.*;
class copy2
{
final static int MAX= 80;
public static void main(String t[]) throws IOException
{
byte b[]= new byte[MAX];
int length;
while((length= System.in.read(b)) > 0)
System.out.write(b, 0, length);
}
}
A program which reads floating point values and calculates the sum of values
averaged over the number of input lines:
import java.io.*;
import java.util.StringTokenizer;
class average
{
final static int MAX= 80;
public static void main(String arg[]) throws IOException
{
byte b[]= new byte[MAX];
int length;
float sum= 0;
int line= 0;
while((length= System.in.read(b)) > 0)
{
StringTokenizer str= new StringTokenizer(new String(b,0));
while (str.hasMoreTokens())
{
String s= str.nextToken();
boolean valid= true;
float f= 0;
try {f= (new Float(s)).floatValue();}
catch(Exception e) {valid= false; }
if (valid) sum += f;
}
if (b[length-1] == '\n') ++line;
}
System.out.println( "Average per line= " + sum/line );
System.in.read(b); // Pause to view result in J++
}
}
Home