[英]Type mismatch when using “while(line = reader.readLine() != null)”
So I am trying to simply print each line of my buffered read to see if It is outputting correctly but I am getting an error in eclipse and at runtime. 因此,我试图仅打印缓冲读取的每一行,以查看其是否正确输出,但是在Eclipse和运行时出现错误。 Absolutely everywhere I look the code for outputting buffered reader is
绝对在我看到的输出缓冲阅读器的代码是
String line;
while(line = myReader.readLine() != null){
{
System.out.println(line);
}
This throws an error saying that "Type mismatch cannot convert from boolean to string." 这将引发错误,指出“类型不匹配无法从布尔值转换为字符串”。 If I change line to a boolean variable it runs and prints "true" three times which is how many lines I am expecting, so does anyone have any idea how I can print the actual text?
如果我将行更改为布尔变量,它将运行并打印三遍“ true”(这是我期望的几行),那么有人知道我如何打印实际文本吗? I am assuming it is throwing the error because != null will return true or false but I cannot get it to work.
我假设它会引发错误,因为!= null将返回true或false,但我无法使其正常工作。
This is because higher Operator Precedence of equality v/s assignment 这是因为等式v / s分配的运算符优先级更高
From the Documentation : 从文档中 :
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first.
当具有相同优先级的运算符出现在同一表达式中时,必须控制一个规则,然后首先评估哪个规则。 All binary operators except for the assignment operators are evaluated from left to right;
除赋值运算符外,所有二进制运算符均从左向右求值; assignment operators are evaluated right to left.
赋值运算符从右到左评估。
(emphasis mine) (强调我的)
So
所以
line = myReader.readLine() != null
Gets evaluated as per precedence as 根据优先级进行评估
line = (myReader.readLine() != null)
which is an attempt to assign boolean to line
, giving the error. 尝试将布尔值分配给
line
,从而给出错误。
(line = myReader.readLine()) != null
while ( (line = myReader.readLine()) != null ) {
will do. while ( (line = myReader.readLine()) != null ) {
会做。 you forgot to put ()
correctly. 您忘记正确输入
()
。
The problem was, myReader.readLine() != null
part was evaluated first. 问题是,
myReader.readLine() != null
部分首先被评估。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.