私は初心者のコーディングクラス用のコードを作成していますが、電子メール検証プロジェクトの部分文字列を作成する際に問題があります。正規表現を探していない、非常に単純な初心者レベルのコーディング。電子メールプロジェクトのJava文字列索引が範囲外です
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);
}
}
}
メールアドレスを入力します。範囲外の文字列インデックス:-1 java.lang.String.substringで (文字列スレッド "メイン" java.lang.StringIndexOutOfBoundsExceptionでprabhu_iastate.edu 例外。 Javaの:1960) email.EMail.main(EMail.java:23で)
最初にここに私の部分文字列に名前を付けるときに、@記号なしでメールアドレスを入力し、私は境界例外のうちを取得する場合は、「文字列の場所= email.substring(atIndex、-1); "このエラーを回避する方法はありますか?
あなたの例外を記述しないで、質問にスタックトレース全体の* exact *テキストを含めてください。 – azurefrog