MODULE 7p - Reading Data
CHARACTER INPUT
The following program reads characters from Standard Input and simply
copies them to the Standard Output. Key it in and try it out.
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
public class InputIntro
{ private static final DataInputStream DIS = new DataInputStream(System.in);
public static void main(String[] args)
{ try
{ while (true)
{ char ch = (char)DIS.readByte();
System.out.print(ch);
}
}
catch(EOFException e)
{ System.out.println("Data Exhausted");
}
catch(IOException e)
{ System.out.println("IOException Encountered");
}
}
}
EXTRACTING NUMBERS FROM SURROUNDING JUNK
The following program reads characters from Standard Input and extracts
sequencs of digits delimited by non-digits and converts them into int
values which are then written out. Key it in and try it out.
import java.io.*;
public class ExtractNumbers
{ private static final DataInputStream DIS = new DataInputStream(System.in);
public static void main(String[] args)
{ try
{ while (true)
System.out.println(fmtInt(readNum(),9));
}
catch(EOFException e)
{ System.out.println("Data Exhausted");
}
catch(IOException e)
{ System.out.println("IOException Encountered");
}
}
private static int readNum() throws EOFException, IOException
{ char ch;
int n=0;
do
{ ch = (char)DIS.readByte();
} while (ch<'0' || '9'<ch);
do
{ n = 10*n + ch - '0';
ch = (char)DIS.readByte();
} while ('0'<=ch && ch<='9');
return n;
}
private static String fmtInt(int n, int d)
{ String s = String.valueOf(n);
while (s.length() < d)
s = " " + s;
return s;
}
}