2017-03-15 143 views
-1

在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(); 
     } 

感謝您的幫助提前!

+1

你是否保證每個數字前都有':'(冒號)? –

+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 
    } 
+0

非常感謝! –

相關問題