【问题标题】:Substring method to identify char value in string value用于识别字符串值中的字符值的子字符串方法
【发布时间】:2021-11-12 04:38:31
【问题描述】:

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

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

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; } 
}

【问题讨论】:

    标签: java string substring


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-12-04
        • 2017-05-13
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        • 2015-10-05
        • 1970-01-01
        • 2016-07-25
        相关资源
        最近更新 更多