ファイルの行数をカウントするプログラムを作成する必要があります。プログラムの起動時にファイルが指定されます。
java CountText textFile.txt
mainメソッドでは、次のコードを使用して、cmdに入力されたファイル名を取得します。
if ( args.length > 0 ) {
String file = args[0];
}
mainメソッドの外で、このファイル名をもう一度参照したいと思います。
public void Lines() throws Exception {
FileReader fr = new FileReader ( file );
シンボルが見つかりません(メインメソッドがパブリックで静的であるため、取得できませんか?)。簡単な解決策のように感じますが、理解できません。
編集:Hovercraft Full Of Eels(またTravis)によって解決されました。これはスコープの問題であり、パラメータを介して文字列をメソッドに渡すことで解決されます。
public class CountText {
public static void main ( String args[] ) throws Exception {
CountText count = new CountText();
if ( args.length > 0 ) {
String file = args[0];
count.Lines( file );
count.Words( file );
count.Characters( file );
}
}
public void Lines ( String file ) throws Exception {
FileReader fr = new FileReader ( file );