2016-11-17 71 views
1

我正在嘗試除了僱傭號碼XXX-L,其中x是範圍0-9中的一個數字,並且L是範圍爲A-M的一個字母。我試圖讓這個代碼工作。但我無法輸入有效的輸入。特殊形式的字符串輸入驗證

import java.util.Scanner; 
import java.util.InputMismatchException; 

public class ObjectOrinetPrograming 
{ 
    public static void main(String [] args) 
    { 
     Scanner input = new Scanner (System.in); 
     System.out.println("Please Enter elements: "); 
     String employeenumber = input.nextLine(); 
     while (employeenumber.length() != 5) 
     { 
      System.out.println("invalid input; lenght, Try again:"); 
      employeenumber = input.nextLine(); 
     } 


      while (employeenumber.charAt(4) != ('A'|'B'|'C'|'D'|'E'|'F'|'G'|'H'|'I'|'J'|'K'|'L'|'M')) 
      { 
       System.out.print("invalid input; charrecter match, try again:"); 
       employeenumber = input.nextLine(); 
      } 


     while (employeenumber.charAt(0) == '-') 
     { 
      System.out.println("Invalid Input; form, try again:"); 
      employeenumber = input.nextLine(); 
     } 
     } 

} 

回答

0

您應該使用matches,這將允許您驗證所有輸入:

import java.util.Scanner; 
import java.util.InputMismatchException; 
public class ObjectOrinetPrograming 
{ 
    public static void main(String [] args) 
    { 
     Scanner input = new Scanner (System.in); 
     System.out.println("Please Enter elements: "); 
     String employeenumber = input.nextLine(); 

     while (!employeenumber.matches("[0-9]{3}-[A-Ma-m]")) { 
      System.out.println("invalid input; lenght, Try again:"); 
      employeenumber = input.nextLine(); 
     } 

    } 

} 
+0

非常感謝好友。 – Muzy

+0

@Muzy我爲你更新了我的答案。 – BlackHatSamurai

+0

@Muzy那麼正則表達式就是** [0-9] {3} - [A-Ma-m] **以符合您的要求。 – m4heshd

1

您可以使用正則表達式來匹配輸入employeenumber

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Please Enter elements: "); 
    String employeenumber = input.nextLine(); 
    while (!employeenumber.matches("[0-9]{3}-[A-M]")) { 
     System.out.println("invalid input; lenght, Try again:"); 
     employeenumber = input.nextLine(); 
    } 

    System.out.println("Your employee id is " + employeenumber); 

} 
+2

小幅盤整。正則表達式應該是** [0-9] {3} - [AM] ** – m4heshd

+0

@iNan非常感謝你,但我試過了,每當我輸入例如:123-A這是正確的輸入,我仍然無效輸入。我認爲你的代碼除了一個字符作爲輸入我想要做的是除了5個字符。不過謝謝你。 – Muzy

+1

@ m4heshd應用編輯工作後。非常感謝你們。 – Muzy