我在创建一类弦乐器问题时要处理两个问题。首先要求是:
- main 代码中输出文件的名称必须是命令行中指定的名称,您可以在其中找到所需的代码。如要求中所述,测试类必须以命令行中的参数启动:
java Mynamep3tst myfilename.txt 这里 myfilename.txt 是所有输出必须去的文件。这个文件名应该在程序中使用如下:
java.io.File 文件 = 新 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 导出非公共类型”。我曾尝试将 public 放在“StringInstrument [] 仪器;”。但是它会弹出错误“非法启动操作”。
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