弦楽器のクラスを作成する問題で扱っている2つの問題があります。まず要件は次のとおりです。
- main のコード内の出力ファイルの名前は、必要なコードがあるコマンド ラインで指定された名前でなければなりません。要件で指定されているように、テスト クラスはコマンド ラインで引数を使用して開始する必要があります。
java Mynamep3tst myfilename.txt ここで myfilename.txt は、すべての出力が必要なファイルです。このファイル名は、プログラムで次のように使用する必要があります。
java.io.File file = new java.io.File(args[0]);
java.io.PrintWriter 出力 = 新しい java.io.PrintWriter(file);
ファイルに送信するメッセージがある場合は、
output.println(メッセージ);
この時点でエラーが発生し続けます。
public static void printInstrumentArray(StringInstrument[] instruments)throws Exception{
java.io.File file = new java.io.File(args[0]);
java.io.PrintWriter output = new java.io.PrintWriter(file);
エラーには「シンボルが見つかりません」と表示されますが、これは配列を宣言していない場合の動作です。配列args []を宣言すると、「スレッド「メイン」java.lang.NullPointerExceptionで例外が発生しました」と表示されます。
次の問題
これを実行すると動作しますが、「パブリック API を介して非パブリック タイプをエクスポートしています」というエラーが表示され続けます。「StringInstrument[]instrument;」に公開を入れてみました。ただし、「不正な操作の開始」というエラーがポップアップ表示されます。
public static void main(String[] args) throws Exception{//begin main //declare instruments StringInstrument[] instruments; //create instrument array instruments = createInstrumentArray(); //Print instrument array printInstrumentArray(instruments); }//end main //Create an array of instrument objects public static StringInstrument[] createInstrumentArray(){//begin method StringInstrument[] instruments = new StringInstrument [10]; //Loop that inputs random integers into the array for (int i = 0; i < instruments.length; i++){//begin loop instruments[i] = new StringInstrument(); }//end loop return instruments; }//End method public static void printInstrumentArray(StringInstrument[] instruments)throws Exception{ java.io.File file = new java.io.File(args[0]); java.io.PrintWriter output = new java.io.PrintWriter(file); //declare and initialize arrays String[] instrumentList = new String [10]; int[] stringNumber = new int [10]; //input string names into array instrumentList[0] = "Guitar"; instrumentList[1] = "Violin"; instrumentList[2] = "Bass Guitar"; instrumentList[3] = "Cello"; instrumentList[4] = "Banjo"; instrumentList[5] = "Sitar"; instrumentList[6] = "Rabab"; instrumentList[7] = "Viola"; instrumentList[8] = "Harp"; instrumentList[9] = "Ukulele"; stringNumber[0] = 5; stringNumber[1] = 4; stringNumber[2] = 5; stringNumber[3] = 4; stringNumber[4] = 5; stringNumber[5] = 18; stringNumber[6] = 3; stringNumber[7] = 4; stringNumber[8] = 47; stringNumber[9] = 4; //Print an array of instruments and their actions for (int i = 0; i < instruments.length; i++){//begin for loop instruments[i].setInstrumentName(instrumentList[i]); output.println(instruments[i].instrumentNameDisplay()); output.println(instruments[i].numberOfStrings(stringNumber[i])); output.println(instruments[i].tuneInstrument()); output.println(instruments[i].playInstrument()); output.println(instruments[i].playInstrumentBand()); output.println(" "); }//end for loop output.close(); }//end method }//end class