Java 如果未检测到“@”符号,则将错误消息打印到屏幕
如果用户输入的电子邮件地址中没有“@”符号,我必须使用if/else语句退出该程序。这是我的这部分代码:Java 如果未检测到“@”符号,则将错误消息打印到屏幕,java,Java,如果用户输入的电子邮件地址中没有“@”符号,我必须使用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 = emailAddres
//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('@'));
如果电子邮件地址不包含@then emailAddress.indexOf'@'返回-1,表示您正在尝试调用emailAddress.substring0,-1
-1不是有效索引,这会导致StringIndexOutOfBoundsException
怎么办
在之前创建用户名,并将其设置为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);
}
哪一个是第51行?当没有匹配的子字符串时,lastIndexOf返回什么?@PM77-1如果没有,则返回-1found@PM77-1返回-1如果未找到子字符串,则返回一个从0到string.sizeString username=emailAddress.substring0,emailAddress.indexOf'@'的数字;在确保字符串带有@符号之前,不要运行此代码。如果电子邮件地址不包含@,则如何使其成为使用if/else语句显示退出消息?这很有效,谢谢!!不过,程序的其余部分仍在运行,有没有办法完全停止它?@Julia Riccio这就是你在寻找的,作为对你最后一条评论的回应。@JuliaRiccio如果你想完全停止代码。使用System.exit0;请参阅更新的答案。@Doc@juliaricio不要使用System.exit0,除非您在main中。它使代码路径不稳定。更好的选择是:构造代码以便可以使用返回,或者抛出异常。@Juliaricio如果这有用,请接受答案。
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);
}