子字符串方法识别字符串值中的字符值

Substring method to identify char value in string value

我有一个创建公司电子邮件域的应用程序,但是,我 运行 在创建一个循环时遇到了一个小问题 运行 一条错误消息,以防用户输入无效字符。

我无法让它与我现有的一起工作,所以我确定我错过了一些重要的东西。

System.out.println("\nEnter name: ");
String name = in.nextLine();

int length = name.length();

for (int x = 0; x < length; x++) {
    
    if(name.substring(x,x+1).equals(".")) {
        
        System.out.println("Error! - name can not contain (.) values\n"
                         + "***************************************************");
        
            System.out.println("\nWould you like to capture another name?" +
            "\nEnter (1) to continue or any other key to exit");
            String opt1 = in.nextLine();

                // If statement to run application from the start 
                if (opt1.equals("1")) {
       
                     System.out.println("menu launch");
                }
                else { System.exit(0); }
    }            
    else { break; } 
}

不要重新发明轮子。您可以只使用 contains 方法,而不是遍历字符串的字符:

if (name.contains(".")) {
    // logic comes here...

虽然 Mureinik 在实现您的目标的最佳方式上是正确的,但您的功能不起作用的原因是您的 else { break; } 声明。

break 终止循环,因此除非第一个字符是 .,否则循环将在第一次迭代后立即退出。当您想增加循环时,正确的关键字是 continue 尽管在这种情况下没有必要,因为所有逻辑都包含在 if 语句中。由于没有其他逻辑可以避免,所以应该删除else语句。