我的程序接收一个文件并将该文件的特定部分添加到不同的数组中。这是我的代码:
public class GradeBookApp {
public static void main(String[] args) throws IOException {
String fileName = "";
String name = "";
char[] categoryCodes = new char[5];
String[] categories = new String[5];
double[] categoryWeights = new double[5];
double[][] gradeTable;
GradeBook myGB = new GradeBook (name, categoryCodes,
categories, categoryWeights);
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
System.out.println("File \"" + args[i]
+ "\" read in and Gradebook object created.");
fileName = args[i];
Scanner scanFile = new Scanner(new File(fileName));
name = scanFile.nextLine();
int numOfCodes = scanFile.nextLine();
for (i = 0; i < 5; i++) {
categoryCodes = scanFile.nextLine().substring(0).toCharArray();
}
}
}
这是文件:
学生1
5
Activity 0.05
q 测验 0.10
p 项目 0.25
电子考试 0.30
f 最终 0.30
a100 a95 a100 a100 a100
q90 q80 q100 q80 q80 r90
p100 p95 p100 p85 p100
e77.5 e88
f92
我正在尝试将粗体代码添加到单独的数组中。字母应该放在类别代码中,单词应该放在类别中,数字应该放在类别权重中。我尝试将第一部分添加到其各自的数组中,但我不确定是否正确执行。另外,我不确定如何将这些行的第二部分和第三部分添加到正确的数组中。
最佳答案
您可以使用split()
方法。
for (i = 0; i < 5; i++) {
String[] all = scanFile.nextLine().split(" ");
if(all.length == 3 && all[0].length() == 1 && all[2].matches("(\\d+\\.\\d+)")){
categoryCodes[i] = all[0].charAt(0);
categories[i] = all[1];
categoryWeights[i] = Double.parseDouble(all[2]);
}
}
关于java - 将一行的特定部分添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499627/