2016-11-19 66 views
0

我想驗證客戶端ID是否只有整數且不重複。 txt文件包含客戶端詳細信息,如id,名稱等。 公共無效loadClientData(){如何驗證java中的txt掃描器數據

String fnm="", snm="", pcd=""; 
    int num=0, id=1; 
    try { 
     Scanner scnr = new Scanner(new File("clients.txt")); 
     scnr.useDelimiter("\\s*#\\s*"); 
     //fields delimited by '#' with optional leading and trailing spaces 

     while (scnr.hasNextInt()) { 
      id = scnr.nextInt(); 
      snm = scnr.next(); 
      fnm = scnr.next(); 
      num = scnr.nextInt(); 
      pcd = scnr.next(); 

      //validate here type your own code 

      if(id != scnr.nextInt()) { 
       System.out.println("Invalid input! "); 
       scnr.next(); 
      } 
     //some code... 
     } 
    } 
} 

只打印出第一個客戶端。

任何幫助請問?

並且它是否已經驗證?

這是client.txt

0001# Jones#   Jack#   41# NX4 4XZ# 
0002# McHugh#   Hugh#   62# SS3 3DF# 
0003# Wilson#   Jonny#   10# LO4 4UP# 
0004# Heath#   Edward#   9# LO4 4UQ# 
0005# Castle#   Brian#   15# LO4 4UP# 
0006# Barber#   Tony#   11# LO4 4UQ# 
0007# Nurg#   Fred#   56# NE8 1ST# 
0008# Nurg#   Frieda#   56# NE8 1ST# 
0009# Mouse#   Mickey#   199# DD33 5XY# 
0010# Quite-Contrary# Mary#   34# AB5 9XX# 
+0

你能告訴我們clients.txt的內容嗎? – vlatkozelka

回答

1

從Java文檔掃描儀類:

公衆詮釋nextInt()

掃描輸入的下一個標記爲int 。

形式nextInt的這種方法(的調用)的行爲在完全相同 方式與調用nextInt(基數),其中基數是此掃描器的 默認基數相同。

返回: 從輸入信息掃描的INT拋出:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range 
NoSuchElementException - if input is exhausted 
IllegalStateException - if this scanner is closed 

如果掃描器讀取無效的輸入不匹配Integer正則表達式的功能將拋出一個InputMismatchException

您可以使用該異常使用try - catch塊驗證和處理「錯誤」你想

您還可以在你的代碼中的其他問題的方式。我修改了它,並在解釋中註釋

public static void loadClientData() { 



try { 
     String fnm = "", snm = "", pcd = ""; 
     int num = 0, id = 1; 
     Scanner scnr = new Scanner(new File("clients.txt")); 
     scnr.useDelimiter("\\s*#\\s*"); 
     //fields delimited by '#' with optional leading and trailing spaces 
     //check for hasNext not hasNextInt since the next character might not be an integer 
     while (scnr.hasNext()) { 

      //here happens the integer validation 

      try { 
       id = scnr.nextInt(); 
      } catch (InputMismatchException ex) { 
       System.out.println("Invalid input !"); 
      } 
      System.out.print(id + " "); 
      snm = scnr.next(); 
      System.out.print(snm + " "); 
      fnm = scnr.next(); 
      System.out.print(fnm + " "); 
      num = scnr.nextInt(); 
      System.out.print(num + " "); 
      pcd = scnr.next(); 
      System.out.println(pcd + " "); 

      //you need to do this to get the scanner to jump to the next line 
      if (scnr.hasNextLine()) {      
       scnr.nextLine(); 
      } 
      //validate here type your own code 
      /* if (id != scnr.nextInt()) { 
      System.out.println("Invalid input! "); 
      //scnr.next(); 
      }*/ 

     } 
    } catch (Exception ex) { 

    } 

}