这是行不通的,我不知道为什么

do {
    System.out.println("enter your work email");
    workEmail = scnr.nextLine();
    if (workEmail.substring(workEmail.length() - 4) != ".") {
        System.out.println("Please enter a valid email. example: JohnDoe@yahoo.com");
    }

} while (workEmail.substring(workEmail.length() - 4) != ".");

===============>>#1 票数:1

您的解决方案有两个主要问题:

  1. 您永远不要使用==!=比较字符串。 使用.equals()或更好的StringUtils.equals()
  2. 当您要使用charAt()时,您正在使用subString() charAt() 虽然chatAr可以工作,但使用.endWith() @YCF_L注释中的解决方案更为出色。

===============>>#2 票数:0

这行可能不正确;

workEmail.substring(workEmail.length() - 4) != "."

如果电子邮件地址为“ johndoe@site.se”,则此操作将失败

如果您确实要确保其以“ .com”结尾,则可以编写如下内容:

String dotcom = ".com";    
if (workEmail.endsWith(dotcom) {...}

===============>>#3 票数:0

使用此代码

!workEmail.substring(workEmail.length() - 4).contains(".")

在您的if条件和while循环中

===============>>#4 票数:0

我会使用RegEx检查电子邮件地址。 以下是一个示例程序:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern emailAddressRegex = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher;

        matcher = emailAddressRegex.matcher("test@test.com");
        System.out.println(matcher.find());

        matcher = emailAddressRegex.matcher("test");
        System.out.println(matcher.find());

        matcher = emailAddressRegex.matcher("test@test.co.uk");
        System.out.println(matcher.find());

        matcher = emailAddressRegex.matcher("test@net");
        System.out.println(matcher.find());

        matcher = emailAddressRegex.matcher("test@test.net");
        System.out.println(matcher.find());
    }
}

输出:

true
false
true
false
true

===============>>#5 票数:0

这就是对我有用的

do {
    System.out.println("enter your work email");
    workEmail = scnr.nextLine();
    if (workEmail.charAt(workEmail.length() - 4) != '.') {
        System.out.println("Please enter a valid email. example: JohnDoe@yahoo.com");
    }

    } while (workEmail.charAt(workEmail.length() - 4) != ('.'));

  ask by jackspurrrr translate from so

未解决问题?本站智能推荐: