2017-02-17 1 views
-3

Je suis en train d'écrire un code pour une classe de codage pour débutants et j'ai de la difficulté à créer une sous-chaîne pour mon projet de validation d'email. Ne cherchez pas regex, juste un très simple codage de niveau débutant.Java String Index hors de portée pour le projet e-mail

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

} 

Entrez une adresse e-mail: prabhu_iastate.edu Exception dans le thread "principal" java.lang.StringIndexOutOfBoundsException: index de chaîne hors de portée: -1 à java.lang.String.substring (String. java: 1960) à email.EMail.main (EMail.java:23)

Si la saisie d'une adresse e-mail sans symbole @ je reçois un hors limites lors de la première exception nommant mon sous-chaîne ici, « emplacement String = email.substring (atIndex, -1); " aucun moyen de contourner cette erreur?

+3

Ne décrivez pas votre exception, incluez le texte * exact * de l'ensemble de la trace de la pile dans votre question. – azurefrog

Répondre

0

Si atIndex est négatif, il lancera (comme dit akos.borads).

Cela provoquera toujours une erreur: String location = email.substring(atIndex, -1);. Vous pourriez vouloir String location = email.substring(atIndex+1, email.length());.

+0

Cela a fonctionné, merci! Pourriez-vous expliquer un peu plus pourquoi le +1 et email.length()? lors de l'introduction de l'emplacement? – Connor

+0

atIndex points à l'index de au caractère, puisque vous voulez l'ignorer, vous devez déplacer une autre position. Ensuite, vous prenez tous les charactes jusqu'à la dernière position qui est à email.lenght() -1 mais le second argument de sous-chaîne est le premier caractère ignoré (pas la dernière prise) donc le premier ignoré est à position (email.lenght() -1) + 1 = email.lenght() – minus

0

Vous devez vérifier si l'e-mail contient le signe @ et ne pas permettre d'aller plus loin, car cela signifie que la validation a déjà échoué.

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