Java String Index超出电子邮件项目的范围

时间:2017-02-17 17:46:17

标签: java substring indexoutofboundsexception

我正在为初学者编写类编写代码,并且无法为我的电子邮件验证项目生成子字符串。不寻找正则表达式,只是非常简单的初级编码。

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 "connoro@iastate.edu" 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   线程&#34; main&#34;中的例外情况java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1       at java.lang.String.substring(String.java:1960)       在email.EMail.main(EMail.java:23)

如果在没有@符号的情况下输入电子邮件地址,我首先在这里命名我的子字符串时会遇到越界异常,&#34;字符串位置= email.substring(atIndex,-1);&#34;任何解决此错误的方法?

2 个答案:

答案 0 :(得分:0)

您必须检查电子邮件是否包含@符号并且不允许更进一步,因为这意味着验证已经失败。

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

答案 1 :(得分:0)

如果atIndex是负数,它将抛出(如akos.borads所说)。

这将始终抛出错误:String location = email.substring(atIndex, -1);

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