Search code examples
javaexceptionioprintwriter

Why is my PrintWriter class not working as expected?


I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!

import java.util.*;
import java.io.*;

class FileReadingExercise3 {

public static void main(String [] args)
{
    Scanner userInput = new Scanner(System.in);
    Scanner fileInput = null;

    String a = null;
    int sum = 0;

    do
    {
        try
        {
            System.out.println("Please enter the name of a file or type QUIT to finish");
            a = userInput.nextLine();

            if(a.equals("QUIT"))
            {
                System.exit(0);
            }

            fileInput = new Scanner(new File(a));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error " + a + " does not exist.");
        }
    }while(fileInput == null);

    PrintWriter output = null;

    try
    {
        output = new PrintWriter(new File("result.txt"));
    }
    catch(IOException g)
    {
        System.out.println("Error");
        System.exit(0);
    }

    while(fileInput.hasNext())
    {
        if(fileInput.hasNextInt())
        {
            int num = fileInput.nextInt();
            sum += num;

            String str = Integer.toString(num);

            output.println(str);

        }
    }

    fileInput.close();
    output.close();
}
}

Solution

  • It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.

    Also you are not using sum so check if you need this variable.

    Here is the code that works:

    public static void main(String[] args) throws FileNotFoundException {
            Scanner userInput = new Scanner(System.in);
            Scanner fileInput = null;
            String a = null;
            int sum = 0;
            do {
                try {
                    System.out
                            .println("Please enter the name of a file or type QUIT to finish");
                    a = userInput.nextLine();
                    if (a.equals("QUIT")) {
                        System.exit(0);
                    }
                    fileInput = new Scanner(new File(a));
                } catch (FileNotFoundException e) {
                    System.out.println("Error " + a + " does not exist.");
                }
            } while (fileInput == null);
    
            PrintWriter output = null;
            try {
                output = new PrintWriter(new File("result.txt"));
            } catch (IOException g) {
                System.out.println("Error");
                System.exit(0);
            }
            while (fileInput.hasNext()) {
                if (fileInput.hasNextInt()) {
                    int num = fileInput.nextInt();
                    sum += num;
                    String str = Integer.toString(num);
                    output.println(str);
                } else {
                    fileInput.next();
                }
            }
            fileInput.close();
            output.close();
        }
    }
    

    Update:

    As per java doc for Scanner.hasNext() method:

    Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

    So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.