我正在开发一个项目,我需要跳过所有以 '"' 开头的行。我有以下代码:
String line = reader.readLine();
boolean containsChar;
try { containsChar = line.charAt(0) != '\"'; }
catch (Exception ex) { containsChar = true; }
while (line != null && containsChar) {
line = reader.readLine();
try { containsChar = line.charAt(0) != '\"'; }
catch (Exception ex) { containsChar = true; }
}
我曾经有一小段代码,但这会检测到行中任何位置包含“”的任何行:
while (line != null && !line.contains("\"")) { line = reader.readLine(); }
我有一个简短的方法来做到这一点,但一行可能为空。在这种情况下,代码返回异常:
while (line != null && line.charAt(0) != '\"') { line = reader.readLine(); }
问题: 是否可以有类似于下面代码的代码,其中 try-catch 位于 while 测试内部?
while (line != null && (try { line.charAt(0) != '\"'; }catch (Exception ex) { true; })) { line = reader.readLine(); }
解决方案: 在其中一条评论中,Thilo 给出了一个可以在任何索引处使用 char 的解决方案(在本例中为索引 12):
( line.length() > 12 && line.charAt(12) == something)
最佳答案
我想你想要String#startsWith
while (line != null && !line.startsWith(quote))
关于Java while 循环 | true 如果测试值返回异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148855/