因此,这是一个基本上取决于args [1]的程序的赋值,它将在命令提示符下显示所需文本文件中的所有内容,并将该文件中的任何内容与计算出的GPA一起写入args [2]中指定的新文件。第二个选项将仅显示GPA,但会将所有内容写入指定的文件。
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class gpahw {
public static void main(String[] args) throws IOException {
double sum = 0;
double numclasses = 0;
if (args.length < 1 || args.length > 3) {
System.out.println("Usage: java gpahw coursestakenn.txt, -o || -fo, new file.");
System.exit(-1);
}
if (args[1].equals("-o")) {
// display only gpa but write classes and gpa to file
File outputfile = new File(args[2]);
PrintWriter write = new PrintWriter(outputfile);
File inputfile = new File(args[0]);
Scanner input = new Scanner(inputfile);
while (input.hasNextLine()) {
String line = input.nextLine();
char letter = line.charAt(line.length() - 1);
if (letter == 'A') {
sum += 4;
} else if (letter == 'B') {
sum += 3;
} else if (letter == 'C') {
sum += 2;
} else if (letter == 'D') {
sum += 1;
}
//System.out.println(line);
numclasses++;
write.println(line);
//write.println("GPA: " + sum / numclasses);
}
write.println("GPA: " + sum / numclasses);
System.out.println("GPA: " + sum / numclasses);
input.close();
write.close();
} else if (args[1].equals("-fo")) {
// display all and write all to file
File outputfile = new File(args[2]);
PrintWriter write = new PrintWriter(outputfile);
File inputfile = new File(args[0]);
Scanner input = new Scanner(inputfile);
while (input.hasNextLine()) {
String line = input.nextLine();
char letter = line.charAt(line.length() - 1);
if (letter == 'A') {
sum += 4;
} else if (letter == 'B') {
sum += 3;
} else if (letter == 'C') {
sum += 2;
} else if (letter == 'D') {
sum += 1;
}
System.out.println(line);
numclasses++;
write.println(line);
}
write.println("GPA: " + sum / numclasses);
System.out.println("GPA: " + sum / numclasses);
input.close();
write.close();
}
if (args.length == 1) {
//supposed to just display what is in file and display calculate GPA
File inputfile = new File(args[0]);
Scanner input = new Scanner(inputfile);
while (input.hasNextLine()) {
String line = input.nextLine();
char letter = line.charAt(line.length() - 1);
if (letter == 'A') {
sum += 4;
} else if (letter == 'B') {
sum += 3;
} else if (letter == 'C') {
sum += 2;
} else if (letter == 'D') {
sum += 1;
}
System.out.println(line);
numclasses++;
}
System.out.println("GPA: " + sum / numclasses);
input.close();
}
}
我在命令提示符中遇到的错误是当我尝试调用&#34; java gpahw courses.txt&#34;时出现的数组索引,这只是显示指定的文本文件中的任何内容显示计算出的GPA,但不向新文件写入任何内容。如果我打电话给#34; java gpahw courses.txt -o coursestaken.txt&#34;该程序可以正常工作。或者相同,除了另一个选项。对不起,如果我的代码非常混乱和冗余。