Search code examples
javaio

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

  • 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]);
            }
        }
    }