1

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();
}
}
Scorpiorian83
  • 469
  • 1
  • 4
  • 17
  • 1
    a) why do you do `new File("result.txt"));` twice? b) your `while(fileInput.hasNext())` followed by `if(fileInput.hasNextInt())` looks dodgy. If the while is true but the if is false then endless loop? – Scary Wombat Aug 25 '14 at 07:20
  • @ScaryWombat oh sorry that was for trial and erroring just now forgot to remove that. erm somehow i'm kinda confused with my while loop like you mentioned lol. – Scorpiorian83 Aug 25 '14 at 07:27
  • but what exactly are your errors? – Scary Wombat Aug 25 '14 at 07:29
  • @ScaryWombat erm the whole thing compiles with no error but when run, it got stuck at right after i input the txt file to be read. – Scorpiorian83 Aug 25 '14 at 07:31

1 Answers1

1

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.

Chaitanya
  • 15,403
  • 35
  • 96
  • 137
  • hey hi thanks for your help here now it works but there is something which I always don't understand which is how come we have to go to the `next()` after that? oh yes i do understand that `sum` variable is unused but i will use it after that thanks for reminding me. :) – Scorpiorian83 Aug 25 '14 at 07:53
  • oh thanks so much for the information but upon reading the `Scanner.next()` it also says that the method may block while waiting for input to scan lol. This is so confusing for me. – Scorpiorian83 Aug 25 '14 at 10:06
  • Suppose if you use `Scanner` to read data entered by the user, then the code looks like this `Scanner s = new Scanner(System.in);` `String data = s.next();` so here the scanner will wait until the user enters some data and hits enter, so in this case scanner is blocked for input. – Chaitanya Aug 25 '14 at 10:09
  • I see... can I ask a favour? Do you think you can have a look at my other question just posted which relates to this application? Thanks again mate! http://stackoverflow.com/questions/25485260/how-do-i-achieve-the-following-results-using-the-printerwriter-class-from-a-text – Scorpiorian83 Aug 25 '14 at 12:05