输入文件以这种方式每次有一行数据:第1行:字符串,第2-4行:整数,第5行:字符串等我需要计数字符串的总数并忽略整数。我怎么能这样做?这里是我的代码:计算.txt输入文件中的字符串出现次数
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileName = in.nextLine();
int stringCounter = 0;
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
String SnumStudents = inputFile.nextLine();
int numStudents = Integer.parseInt(SnumStudents);
Student [] studentList = new Student[numStudents];
for (int i = 0; i < numStudents; i++)
{
String line = inputFile.nextLine();
String score1 = inputFile.nextLine();
String score2 = inputFile.nextLine();
String score3 = inputFile.nextLine();
studentList [i] = new Student(line, Integer.parseInt(score1), Integer.parseInt(score2), Integer.parseInt(score3));
}
System.out.println("Name\t\tScore1\tScore2\tScore3\tTotal");
System.out.println("---------------------------------------------");
for (int i=0; i< studentList.length;i++){
System.out.println(studentList[i].getName() + "\t" + studentList[i].getScore1() + "\t" + studentList[i].getScore2() + "\t" + studentList[i].getScore3() + "\t" + studentList[i].getTotal());
}
System.out.println("---------------------------------------------");
Integer i = Integer.valueOf(SnumStudents);
stringCounter++;
System.out.println(stringCounter);
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + fileName);
}
finally {
}
in.close();
}
}
输入文件:
9
Andy Borders
200
250
400
John Smith
120
220
330
Alvin Smith
225
300
278
请参阅正则表达式(正则表达式) – NickJ 2014-12-05 15:46:55
我们还没有教过关于使用它。我需要一种本质上是初学java的方法。 – 2014-12-05 15:49:51
我无法弄清楚如何让它只添加字符串而不是整数。 – 2014-12-05 15:50:50