2017-02-17 57 views
-3

我正在寫一個初學者編碼類代碼時遇到生產我的電子郵件驗證項目的子麻煩。不尋找正則表達式,只是非常簡單的初學者級別的編碼。在java.lang.String.substring(字符串-1 : 異常線程 「main」 java.lang.StringIndexOutOfBoundsException prabhu_iastate.edu:字符串索引超出範圍Java的String指數超出範圍的電子郵件項目

package email; 
import java.util.Scanner; 

/** 
* Input: An email address of your choosing 
* Output: If the email is valid, return, "Valid" If invalid, return "Invalid." 
* An input of "[email protected]" would return valid because of all the requirements an address should have is present 
*/ 

public class EMail { 

    public static void main(String[] args) { 

     System.out.print("Enter an email address: ");//input prompt 
     String bad = "Email is invalid";//shows if email is invalid 
     String good = "Email is valid";//shows if email is valid 
     Scanner In = new Scanner(System.in);//Reads input from user 
     String email = In.next();//read the input into a String variable using In as the Scanner 
     int atIndex = email.indexOf('@');//shows location of '@' character 
     int lastDotIndex = email.lastIndexOf('.');//shows location of the last'.' in email String 
     int dotIndex = email.indexOf('.');//shows the location of the character of '.' 
     String location = email.substring(atIndex, -1); 

     if((atIndex == -1) ||(dotIndex == -1)){//If the input email does not have '@' or "." it is invalid 
      System.out.println(bad); 
     } 
     else if(atIndex == 0){//if the character'@' is the first character 
      System.out.println(bad); 
     } 
     else if(dotIndex == email.length()-1){//if the '.' is the last character the email is invalid 
      System.out.println(bad); 
     } 
     else if(lastDotIndex < atIndex){//if the last "." is before the '@' symbol the email is invalid 
      System.out.println(bad); 
     } 
     else if(email.lastIndexOf('.') < email.indexOf('.')){//if the first '.' is the last character the email is invalid 
      System.out.println(bad); 

     } 
     else if((location.length()== -1)|| location.length() <= 0){//If there is no string between the '@' char & the last '.' 
      System.out.println(bad); 
     } 
     else{ 
      System.out.println(good); 
      System.out.println(location); 
      } 
    } 

} 

輸入電子郵件地址。 Java的:1960) 在email.EMail.main(EMail.java:23)

如果沒有一個@符號輸入電子郵件地址,我得到一個出界異常時,首先命名我的子在這裏,「字符串位置= email.substring(atIndex,-1);「繞過這個錯誤的任何方法?

+3

不要描述你的異常,包括*確切*在你的問題整個堆棧跟蹤的文本。 – azurefrog

回答

0

如果atIndex爲負,它會拋出(as akos.borads said)。

這將始終拋出錯誤:String location = email.substring(atIndex, -1);

也許你想String location = email.substring(atIndex+1, email.length());

+0

這工作,謝謝!你能解釋一下爲什麼+1和email.length()?何時介紹位置? – Connor

+0

atIndex指向字符的索引,因爲您想跳過它,所以您需要移動一個位置。 然後你把所有的本地字符到最後一個位置(),這是在email.lenght -1但串第二個參數是第一個跳過字符(不是最後拍攝),因此第一跳是在位置(email.lenght() -1)+ 1 = email.lenght() – minus

0

您必須檢查電子郵件包含@符號,不允許走的更遠,因爲這意味着驗證已經失敗了。

int atIndex = email.indexOf('@'); 
if (atIndex < 0) { 
    System.out.println(bad); 
    return; 
}