2014-10-31 98 views
0

我試圖做一個小程序,它會從文件中讀取輸入並打印出來,如果他們匹配特定的格式是:掃描文件驗證

Team Name : Another Team name : Score : Score 

這裏是我做了什麼等等到目前爲止,如果你能在正確的方向指向我,我會很感激

import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 

public class Generator { 

    public static void main(String[] args) throws FileNotFoundException{ 

     String file; 
     Scanner fileScan; 
     fileScan = new Scanner (new File("document.txt")); 
     int count = 0; 

     while (fileScan.hasNextLine()){ 
      file = fileScan.nextLine(); 
      System.out.println(file); 
      count++; 

     } 

     System.out.println(count+ " number of lines successfully validated"); 

    } 

} 

我想程序驗證格式是否有效,如果不是不打印線,但保持數所以我可以在最後輸出多少行未被正確驗證。

謝謝。

+0

什麼是你期望 – kirti 2014-10-31 14:45:11

回答

0

String#split()length數組的屬性是在這裏使用的工具。

我離開你,找出如何正確使用它們。

2

這是非常簡單的檢查使用String.matches(regexPattern)。使用另一個變量來保持無效行數。

int invalidLines = 0; 
String line =null; 
while (fileScan.hasNextLine()){ 
     line = fileScan.nextLine(); 
     if(!line.matches(regexPattern)){ 
       invalidLines++; 
     } 
     count++; 
} 

使用\w+一個字匹配和\d+的數字。

Read more about regex on StackOverflow

0
public static void main(String[] args) throws FileNotFoundException{ 
int invalidcount=0; 
     String file; 
     Scanner fileScan; 
     fileScan = new Scanner (new File("document.txt")); 
     int count = 0; 
String arrTeam[]={ "",""}; // create arrTeam array with the valid inputs in it 

    while (fileScan.hasNextLine()){ 
      file = fileScan.nextLine(); 
for(inti=0;i<arrTeam.length;i++) // have a loop on the array here 
{ 
if(arrTeam[i]=!file){ //if the input is not in the array increase the invalid count 
    invalidcount++; 

} 
    }  else 
{ 
System.out.println(file); 
} 
      count++; 

     } 

     System.out.println(count+ " number of lines successfully validated"); 
System.out.println(invalidcount+ " number of lines unsuccessful"); // print them here 
    } 
0

您可以使用正則表達式,如果返回true,以配合您的輸入,然後,如果爲假,則它不符合防爆您的輸入相匹配。

String test = "TeamA:TeamB:44:99"; 
System.out.println("" + test.matches("\\D+[:]\\D+[:]\\d+[:]\\d+")); 

這將匹配非數字:非數字:數字:數字

+0

另一支球隊的名字可以是多的話,以及有效的輸入。 – Braj 2014-10-31 15:00:22