2017-05-09 26 views
1
public static void emailChecker() { 
    Scanner input = new Scanner(System.in); 
    String email = " "; 
    char[] test; 
    int counter = 0; 

    System.out.println("Please enter your email: "); 
    email = input.nextLine(); 

    test = email.toCharArray(); 

    for (int i = 0; i < email.length(); i++) { 
     if (test[i] == 64 || test[i] == 46) { 
      System.out.println("Email is valid"); 
     } else { 
      System.out.println("Email is not valid"); 
     } 
    } 

} 

我發現在第10行輸出會說如果字符串包含一個「。」,那麼email將是有效的。或「@」。但是我希望我的代碼只在「。」時表示該字符串是有效的。在「@」之後。有效的電子郵件示例是:[email protected]如何檢查「。」在java中「@」之後?

+0

使用正則表達式,你可以做一個更好的驗證器:http://stackoverflow.com/questions/8204680/java-regex-email。看到這個答案。 –

+0

不......這不是一個很好的電子郵件驗證方式。相反,看看使用正則表達式。有_many_其他無效的輸入,你的例子沒有打算涵蓋。 –

+0

我只應該使用數組來檢查它是否工作。但我沒有理解它背後的邏輯。 – Lance

回答

0

試試這個,它會給你輸出。

public static void emailChecker() { 
     Scanner input = new Scanner(System.in); 
     String email = " "; 
     char[] test; 
     int counter = 0; 

     System.out.println("Please enter your email: "); 
     email = input.nextLine(); 

     test = email.toCharArray(); 
     boolean valid = false; 

     for (int i = 0; i < email.length(); i++) { 
      if (test[i] == 64){ 
       for(int y=(i+1); y<email.length(); y++){ 
        if(test[y] == 46){ 
         valid = true; 
        } 
       } 
      } 
     } 

     if(valid == true){ 
      System.out.println("Email is valid"); 
     }else{ 
      System.out.println("Email is not valid"); 
     } 
} 
+0

非常感謝,完全有道理。 Idk爲什麼我沒有想到這一點。 – Lance

0

正則表達式是驗證電子郵件ID格式最簡單的方法。如果你想好工作示例,請參閱

https://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

如果你還想去與字符數組的比較,這裏使用兩個附加的int變量有過驗證的精細控制的樣本代碼..

public static void emailChecker() { 
    Scanner input = new Scanner(System.in); 
    String email = " "; 
    char[] test; 
    System.out.println("Please enter your email: "); 
    email = input.nextLine(); 
    test = email.toCharArray(); 

    int fountAtTheRateAt = -1; 
    int fountDotAt = -1; 

    for (int i = 0; i < email.length(); i++) { 
     if (test[i] == 46) { 
      fountDotAt = i; 
     } else if (test[i] == 64) { 
      fountAtTheRateAt = i; 
     } 
    } 
    // at least 1 char in between @ and . 
    if (fountDotAt != fountAtTheRateAt && (fountAtTheRateAt+ 1) < fountDotAt) { 
     System.out.println("Email is valid"); 
    } else { 
     System.out.println("Email is not valid"); 
    } 
    input.close(); 
} 
0

下面是使用循環的問題的一個答案。

但是,正如其他人所評論的,這不是驗證電子郵件地址的方法。

boolean foundDot = false; 
boolean foundAt = false; 

for (char c: test) { 
    if (!foundAt) { 
     foundAt = (c == '@'); \\ the () brackets are not required, but makes the code easier to read. 
    } else { 
     foundDot = (c == '.'); 
    } 

    if (foundDot) { 
     valid = true; 
     break; 
    } 
} 
相關問題