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 = 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/

相关文章:

java - Akka 的 ActorSystem 关闭?

java - Java程序中的位置计数问题

java - OSX 上 JAR 文件的推荐位置

java - 如何在 Android (Java) 中使用 Esc Pos 打印图像

Java - Intellij 无法编译 GUI - 退出值 1

java - 如何根据条件有选择地从数组列表中删除值?

java - 如何将传递的 c++ 长指针转换为 java 指针或数组

java - 接受用户输入和调用方法的设计模式

java - 谷歌应用引擎 500 错误

java - 调用 pack() 后如何在面板上画一条线?