2017-02-17 16 views
-3

Я пишу код для класса кодирования новичков, и у меня возникают проблемы с созданием подстроки для моего проекта проверки электронной почты. Не искать регулярное выражение, просто очень простое кодирование начального уровня.Java String Index вне диапазона для проекта электронной почты

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); 
      } 
    } 

} 

Введите адрес электронной почты: prabhu_iastate.edu Исключение в потоке "основного" java.lang.StringIndexOutOfBoundsException: индекс Струнный вне диапазона: -1 в java.lang.String.substring (String. Java: 1960) в email.EMail.main (EMail.java:23)

Если ввод адреса электронной почты без символа @ я получить из исключения границ, когда первый называя мою подстроку здесь, «расположение строк = email.substring (atIndex, -1); " в любом случае вокруг этой ошибки?

+3

Не описывайте свое исключение, укажите * точный * текст всей трассировки стека в своем вопросе. – azurefrog

ответ

0

Если atIndex отрицательный, он будет кидать (как сказал akos.borads).

Это всегда вызовет ошибку: 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; 
}