2017-02-19 34 views
1

我正在研究一個程序,當您輸入錯誤的電子郵件時,它會顯示一條錯誤消息。如果它是空的,該消息會告訴你它不能爲空。如果超過30個字符,則必須小於或等於30,依此類推。我遇到的程序是我從來沒有在If語句中使用indexOf。如果輸入的電子郵件地址只能有一個AtSign(@),我該如何編碼?或代碼,如果沒有@符號或有超過2,將顯示一條錯誤消息。如何在Java中使用If語句使用indexOf?

import javax.swing.JOptionPane; 


public class EmailandGrade { 

public static void main(String[] args) { 

     // 1. Declaring Variables 

     String strEmail; 



     // 2. Print Prompts and User Input 
     strEmail = JOptionPane.showInputDialog("Enter a user email:"); 

     // 3. If/Else Statements For Email 
     if (strEmail.isEmpty()) 
     { 
      JOptionPane.showMessageDialog(null, "Can't be blank"); 
     } 
     else if (strEmail.length() > 30) 
     { 
      JOptionPane.showMessageDialog(null, "Email must be less than or equal 30 characters"); 
     } 
     else if (!strEmail.endsWith("@student.stcc.edu")) 
     { 
      JOptionPane.showMessageDialog(null, "Must end with in: @student.stcc.edu"); 
     } 
     else if (strEmail.indexOf("@")) 
     { 
      JOptionPane.showMessageDialog(null, "Can only have one @ in it"); 
     } 

回答

2

如果String.indexOf(String)沒有找到作爲鏈接的Javadoc指出它返回-1所請求的子字符串。所以,你可以測試像,

else if (strEmail.indexOf("@") == -1) 

然後,你需要編寫另一個測試,以檢查是否有兩個(或更多)@跡象。也許使用String.lastIndexOf(String)一樣,

else if (strEmail.indexOf("@") == -1 || 
     strEmail.indexOf("@") != strEmail.lastIndexOf("@")) 
+0

感謝它的工作。 – Drizzy

+0

@Drizzy如果您的問題得到解答,請[接受](http://meta.stackexchange.com/a/5235/243725)您發現的答案最有幫助。 –

0
else if (strEmail.indexOf("@") != -1) 

如何使用的indexOf一個例子是恰到好處以上。基本上,indexOf返回字符串的索引(如果找到)。然後,如果沒有找到,則返回-1。

2

如果你想檢查有效的電子郵件。有兩種方法來檢查它。 1.手動檢查字符串不是空的有效長度,模式和其他東西。 2.可以使用Java的模式和Matcher.That的唯一的建議

答案1.

String.indexOf(character)方法返回該字符串指定字符或-1第一次出現處的索引,如果字符不發生。所以,你需要添加

else if (strEmail.indexOf("@") == -1) 

答2. 你只需要設置正則表達式驗證電子郵件地址。

public class EmailValidator { 

    private Pattern pattern; 
    private Matcher matcher; 

    private static final String EMAIL_PATTERN = 
     "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" 
     + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 

    public EmailValidator() { 
     pattern = Pattern.compile(EMAIL_PATTERN); 
    } 

    public boolean validate(final String hex) { 

     matcher = pattern.matcher(hex); 
     return matcher.matches(); 

    } 
}