gpt4 book ai didi

java - 我的代码正在为我的 BufferedReader 和 FileReader 返回一个字符串到 boolean 值和 boolean 值到字符串错误,我的错误在哪里?

转载 作者:行者123 更新时间:2023-12-02 14:56:18 24 4
gpt4 key购买 nike

这是我的代码:

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;

public class SymbolBalance{
public static void main(String[] args) throws Exception{
File givenFile = null;
String words = null;

if(args.length > 0){
givenFile = new File(args[0]);
} else{
System.out.println("Error! No file name was given!");
}
BufferedReader scan = new BufferedReader(new FileReader(givenFile));

while(words = scan.readLine() != null){
System.out.println(words);
}
scan.close();
}
}

这是我的错误:

codio@titanic-avenue:~/workspace$ javac SymbolBalance.java
SymbolBalance.java:21: error: incompatible types: boolean cannot
be converted to String
while(words = scan.readLine() != null){
^
SymbolBalance.java:21: error: incompatible types: String cannot
be converted to boolean
while(words = scan.readLine() != null){

我正在尝试从命令行获取一个文件,扫描它,然后在终端中逐行打印出文件中的内容。我知道 bufferedreader 不能直接与字符串一起工作,这是我使用 FileReader 的原因,但我仍然得到 boolean 值到字符串和字符串到 boolean 值的错误。有人可以指出我发现此错误的正确方向吗?

最佳答案

你必须用大括号把赋值括起来,像这样:

while ((words = scan.readLine()) != null)

原因是Java中赋值运算符的优先级低于非等号运算符的优先级。事实上,赋值运算符的优先级是最低的。更多详情可以看https://introcs.cs.princeton.edu/java/11precedence/

关于java - 我的代码正在为我的 BufferedReader 和 FileReader 返回一个字符串到 boolean 值和 boolean 值到字符串错误,我的错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52752484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com