【问题标题】:Check if lines in a file only starts with "@" or "-"检查文件中的行是否仅以“@”或“-”开头
【发布时间】:2014-09-08 12:44:25
【问题描述】:

我将读取带有BufferedReader()readLine() 的文件。 结果将写入ArrayList<String>

如果以“@”或“–”开头,我将检查 .txt 中的每一行。 如果不是 InvalidFormatException 应该被抛出。

for(String s:Data) {
    if (!s.startsWith("@") || !s.startsWith("-"))
        throw new InvalidFormatException("Invalid Format");
}

我的 .txt 看起来像:

@1.2.1
- new feature @1.2.0
- new picture

所以它应该只在“@”或“-”是一行的开始字符时才有效

@1.2.1
- new feature 
new picture

这个例子应该抛出一个异常

我每次尝试都会遇到异常。

有隐藏角色吗?

【问题讨论】:

    标签: java bufferedreader readline


    【解决方案1】:

    几乎。您的条件是“如果不以@ 开头或不以- 开头”。

    尝试改用&&(和):

    if (!s.startsWith("@") && !s.startsWith("-"))
    

    【讨论】:

      【解决方案2】:

      您使用的布尔运算符是OR

      您的条件将检查它是否不以第一个字符开头,OR 如果不以第二个字符开头。

      由于您要检查的内容不是以两者开头,因此您必须使用AND

      将您的代码替换为:

      if (!s.startsWith("@") && !s.startsWith("-"))
      

      【讨论】:

        【解决方案3】:

        你的条件不对,如果第一个字符不是'@'并且不是'-',你想抛出Exception。使用这个:

        if (!s.startsWith("@") && !s.startsWith("-"))
            throw new InvalidFormatException("Invalid Format");
        

        顺便说一句,如果您只测试第一个字符,您可以这样做:测试第一个字符而不检查字符串匹配(在这种情况下,您还必须检查是否有第一个字符:非空):

        if (s.isEmpty() || (s.charAt(0) != '@' && s.charAt(0) != '-'))
            throw new InvalidFormatException("Invalid Format");
        

        【讨论】:

          【解决方案4】:

          我使用 RegEx 修复了它

          for(String s:Data) {
                      if (s.matches("[^@-].*$"))
                          throw new InvalidFormatException("wrong Format");
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-11-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-10
            • 2022-09-23
            • 2011-05-24
            • 2012-02-15
            相关资源
            最近更新 更多