在java中,如何只读取文件中的数据,并忽略前面的字符串?伙计们,我做了很多研究,但我似乎无法找到它。
这是一个示例文本文件:
number of courses:3
course numbers:219 214 114
arrival Probabilities:0.4 0.6 0.8
min time:2
max time: 4
num cups:1
simulation time:50
number of tas:2
现在你们可以看到,我只想阅读数字。
我当前的代码如下,但由于显而易见的原因我遇到了InputMismatchException(它首先读取字符串而不是整数):
//Read file
while(input.hasNext()){
//Read Number of Courses
numCourses = input.nextInt();
courseNumbers = new int[numCourses]; //Initialize the size of courseNumbers array.
arrivalProbability = new double[numCourses]; //Initialize the size arrivalProbability array.
//Read the CourseNumbers, numCourses times.
for(int i = 0; i < numCourses; i++){
courseNumbers[i] = input.nextInt();
}
//Read the arrivalProbability, numCourses times.
for(int i = 0; i < numCourses; i++){
arrivalProbability[i] = input.nextDouble();
}
//Read minTime
minTime = input.nextInt();
//Read maxTime
maxTime = input.nextInt();
//Read number of Coffee cups
numCups = input.nextInt();
//Read simulation time
officeHrTime = input.nextInt();
//Read the number of TAs
numTAs = input.nextInt();
}
提前感谢您的帮助!
答案 0 :(得分:1)
我会这样做:
请勿使用nextInt
,请使用nextLine
。您需要进行比我在此处包含的错误检查更多的错误检查,但我会这样做:
int numCourses;
int[] courseNumbers; // I would use a list here, but sticking with your data types for clarity.
while(input.hasNextLine()) {
String line = input.nextLine();
String[] lineParts = line.split(":");
String label = lineParts[0];
String value = lineParts[1];
if(label.equals("number of courses")) {
numCourses = Integer.parseInt(value);
} else if(label.equals("course numbers")) {
String[] courseNumberStr = value.split(" ");
courseNumbers = new int[numCourses]; // you probably want to make sure numCourses was set and courseNumStr has the correct number of elements
for(int i = 0; i < courseNumberStr.length; i++) {
courseNumbers[i] = Integer.parseInt(courseNumberStr[i]);
}
} else if( /* handle the rest of the inputs */) {
// etc
}