2 Replies - 374 Views - Last Post: 09 August 2017 - 01:13 AM Rate Topic: -----

#1 Reb14  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-July 17

Writing to a file

Posted 08 August 2017 - 08:52 PM

I want to write 10 random number ranging from 1 - 10 ising the ;ten times but when I check my txt file it only writes the first code then it stops and doesn't print the rest. Here's what I got.
java.io.File file = new java.io.File("data_TorresUzziel.txt");

for(int i = 0; i < 10; i++){
java.io.PrintWriter output = new java.io.PrintWriter(file);
   random = number.nextInt(10) + 1;	
		
output.println("index " + i + = " = " + random);
		System.out.println("Index " + i +  " = " + random);
		output.close();
		}



Is This A Good Question/Topic? 0
  • +

Replies To: Writing to a file

#2 ndc85430  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 541
  • View blog
  • Posts: 2,201
  • Joined: 13-June 14

Re: Writing to a file

Posted 08 August 2017 - 09:52 PM

Why are you creating a PrintWriter on each iteration of the loop? That only needs to be done once. Likewise, why are you closing it on each iteration of the loop? That also only needs to be done once.

This post has been edited by ndc85430: 09 August 2017 - 01:37 AM

Was This Post Helpful? 0
  • +
  • -

#3 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3417
  • View blog
  • Posts: 15,410
  • Joined: 20-September 08

Re: Writing to a file

Posted 09 August 2017 - 01:13 AM

Also, import your classes - don't use their fully-qualified names or it just makes your code cluttered
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1