Reputation: 1
I am trying to print even numbers from a input.txt file to a display.txt output file. Anytime I send the output to the output console as a test it works perfect. It shows the even numbers. Anytime I use print stream and send it to a file, it only prints out the last even number.
I've researched and asked my professor who says they do not know what is wrong.
Scanner inputfile=new Scanner(new File("input.txt"));
double sum=0.0;
int count=0;
while (inputfile.hasNext())
{
if(inputfile.hasNextInt())
{
int next=inputfile.nextInt();
int even=(next%2);
if(even==0)
{
PrintStream output=new PrintStream(new File("display.txt"));
output.println(next);
System.out.println(next);
count++;
}
}
else
{
inputfile.next();
continue;
}
}
if(count>0)
{
inputfile.close();
}
else
{
System.out.println("The file doesn't contain any integers. Exit
Program");
}
Expected output is all even numbers to the display.txt file. Only the last one prints in the file.
Upvotes: 0
Views: 24
Reputation: 5239
This is because you're instantiating PrintStream
in every loop of your while
loop, you want to instantiate PrintStream output = new PrintStream(new File("display.txt"));
before you start your while loop.
Eg:
// More code
PrintStream output = new PrintStream(new File("display.txt"));
while (inputfile.hasNext())
{
if (inputfile.hasNextInt())
{
int next = inputfile.nextInt();
int even = (next % 2);
if (even == 0)
{
output.println(next);
System.out.println(next);
count++;
}
}
else
{
inputfile.next();
continue;
}
}
// More code
Upvotes: 4