Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Array of Array
|
Posted: Apr 14, 2002 2:03 PM
|
|
Below is some code that will read a text file into an array of String (and print it back out with numbered lines, so you know it is working).
You did mean array of String, not array of arrays didn't you?
Why is your class called AlphabetDriver, if what you want it to do is read files?
It is not a nice thing to have main() simply throw the exceptions. It is better to handle them yourself and try to either resolve the problem or produce some message that will help the user understand or solve the problem (stack traces don't help much, usually, unless the user is the programmer).
Why is String variable you use to read the lines called "letter" when it is reading entire lines, not a single letter?
Why would you ever use a variable name like "stdin" for a named file you are reading? The only purpose that could serve is to confuse people who are reading the code.
Are you using some class called SimpleInput that you didn't include with your post? Assuming you have this class and it works as expected, you would still only print out the first line of the file (or "null" for an empty file), followed by a "#" (I don't know why you want to print that at the end).
import java.util.List;
import java.util.ArrayList;
import java.text.NumberFormat;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
class FileLister
{
public static void main( String [] args )
{
if( args.length > 0 )
{
String [] lines = getStringArrayFromFile( args[0] );
printLinesWithNumbers( lines );
}
else
System.out.println("Specify a file to list.");
}
static String [] getStringArrayFromFile( String filename )
{
// I'm using a list, because I don't know how many
// lines there will be in the file. You can keep
// appending to a List, unlike an array.
List lineList = new ArrayList();
try
{
BufferedReader reader = new BufferedReader( new FileReader( filename ) );
String line = reader.readLine();
while( line != null )
{
lineList.add(line);
line = reader.readLine();
}
}
catch( FileNotFoundException fnfe )
{
System.out.println("Can't find the file " + filename + ".");
}
catch( IOException ioe )
{
System.out.println("IOException while reading " + filename + ".");
}
return (String[])lineList.toArray( new String[0] );
}
static void printLinesWithNumbers( String [] lines )
{
for( int i = 0; i <= lines.length; i++ )
System.out.println( rightJustify(i+1,lines.length) + ". " + lines[i] );
}
static String rightJustify( int value, int maxValue )
{
StringBuffer result = new StringBuffer();
String valueString = Integer.toString(value);
int length = valueString.length();
int maxLength = Integer.toString(maxValue).length();
for( int i = length; i < maxLength; i++ )
result.append(" ");
result.append(valueString);
return result.toString();
}
}
|
|