Java while 循环 | true 如果测试值返回异常错误

标签 java loops while-loop try-catch

我正在开发一个项目,我需要跳过所有以 '"' 开头的行。我有以下代码:

 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/

相关文章:

C++,得到一个无限循环

PHP WHILE 循环神秘地没有产生任何输出

C 编程——循环

java - 在 Java Netbeans 生成的组合框中添加元素

java - 专用服务器 : why can't my JAVA application connect to my MySQL database?

java - 二维数组无法移动

java - 在正则表达式中匹配电话号码

c# - 非常简单的代码中类、结构或接口(interface)成员声明中的无效标记 'while'

php - Foreach 循环和 XML-RPC : It should work but it isn't, 为什么?

java - 循环不能正常工作