2

Here is my code:

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();
    }
}

Here is my error:

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){

I'm trying to take in a file from the command line, scan it, then print out what the file says line by line in the terminal. I know that bufferedreader doesn't work directly with Strings, which is my reason for using FileReader, but yet I still get a boolean to string and string to boolean error. Can someone point me in the right direction in finding this error?

2
  • 1
    Post you code here as text Commented Oct 11, 2018 at 4:56
  • Got it, will edit now.
    – kgb86
    Commented Oct 11, 2018 at 4:56

1 Answer 1

7

You have to surround assignment with braces, like this:

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

The reason is that precedence of assignment operator in Java is lower than the precedence of nonequality operator. As the matter of fact, precedence of assignment operator is the lowest possible. For more details you can look at https://introcs.cs.princeton.edu/java/11precedence/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.