Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep my code from printing null to the command line when out of lines of text?

My code needs to stop printing when the text in the file runs out. Right now it prints out null until it hits 100. My assignment wants it to stop taking in when there is nothing else to print.

import java.io.*;
import java.util.Scanner;
public class TextFileReader {
    
    String[] stringArray = new String [100];
    
    TextFileReader() {
        
    }
    
    TextFileReader(String fileName) {
        
        try {
            
            FileInputStream fis = new FileInputStream(fileName);
            Scanner scan = new Scanner(fis);
        
            for(int i = 0; i < stringArray.length || scan.hasNextLine(); i++) {
                if(scan.hasNextLine()){
                    stringArray[i] = scan.nextLine();
                }   
            }
        }
        
        catch(IOException e) {
            e.printStackTrace();
        }
    }
    
    public String contents(String fileName) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < stringArray.length; i++) {
            sb.append(stringArray[i]);
            }
        return sb.toString();
    }
    
    public void display(String fileName) {
        for(int i = 0; i < stringArray.length; i++) {
            System.out.println(i + ": " + stringArray[i]);
            }
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your problem is not that you are reading wrongly it is that you are displaying wrong. You initialize stringArray = new String [100]; meaning that it will have 100 nulls at the beginning. And after you are done reading if you read less than 100 lines you will still have nulls when you call display(String fileName)

Solution is to stop displaying when you reach empty indexes

public void display(String fileName) {
    for(int i = 0; i < stringArray.length; i++) {
        if(stringArray[i] == null) break;
        System.out.println(i + ": " + stringArray[i]);
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading