如果用户输入的电子邮件地址不包含“@”符号,我必须使用 if/else 语句退出程序。这是我这部分的代码:
//prompt user for their email address
System.out.print("\nPlease enter your email address: ");
//read user's input
emailAddress = keyboard.next();
//create username
String username = emailAddress.substring(0, emailAddress.indexOf('@'));
//create username
atSign = emailAddress.lastIndexOf("@");
if(atSign >= 0){
username = emailAddress.substring(0, atSign);
}
else{
System.out.print("You've entered an invalid email address!");
System.out.println("Goodbye!");
}
错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at Riccio_Lesson6.main(Riccio_Lesson6.java:51)
最佳答案
String username = emailAddress.substring(0, emailAddress.indexOf('@'));//this will throw exception
要做什么?
之前创建用户名
并将其设置为null
或空字符串。然后检查该符号是否存在。
String username = null;
// or String username = "";
//create username
atSign = emailAddress.lastIndexOf("@");
if(atSign >= 0){
username = emailAddress.substring(0, atSign);
}
else{
System.out.print("You've entered an invalid email address!");
System.out.println("Goodbye!");
// use return to stop code here if in a method(better choice) or
// if in the main() uncomment the code below
// System.exit(0);
}
关于java - 如果未检测到 '@' 符号,则将错误消息打印到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565216/