+ 1

HELP: What's wrong with my code - Java

Hi guys, I would really appreciate as to why my code isn't working. So, I basically want this code to randomly generate a list of numbers and then write these numbers to a file. The code to "randomly generating numbers" works perfectly fine, however, the code for "writing to a text file" doesn't write a list of numbers to a text file, but simply only one number appears and is written. Below is my code: ----------------------------------------------------------------------------------------------------------------------------------------- import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; public class ThreadB { public static void main(String[] args) throws IOException{ Random numGenerator = new Random() ; for(int counter=1; counter<=50; counter++) { int number = 1 + numGenerator.nextInt(400); System.out.println(number); PrintWriter out = new PrintWriter(new FileWriter ("random.txt")); out.println(number++); out.close(); } } } ----------------------------------------------------------------------------------------------------------------------------------------- However this persons code works, but not mine. ----------------------------------------------------------------------------------------------------------------------------------------- import java.io.FileNotFoundException; import java.io.PrintWriter; public class WriteFile { public static void main(String[] args) throws FileNotFoundException { PrintWriter out = new PrintWriter("random.txt"); int line = 1; while (line <= 100) out.println((line++) + ": " + Math.random()); out.close(); } } -----------------------------------------------------------------------------------------------------------------------------------------

30th Apr 2018, 3:30 PM
ASDFG
ASDFG - avatar
6 Answers
+ 3
The file might not be getting over-written each time you reset its pathÂż Try placing PrintWriter out = new PrintWriter("random.txt"); Before the loop. and out.close() after the loop.
30th Apr 2018, 4:00 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
You see that plus on the right in the cirkle of where you type your respones? There you can select insert code. Under the codes tab in your profile you can insert a code. When you have done that you can select and insert it here (filter on: my codes) :) Like this: https://code.sololearn.com/cdIrgNmSIlb1/?ref=app
30th Apr 2018, 3:51 PM
***
*** - avatar
+ 1
next time, post your code as code, not as text, makes it way more easy to answer your question.
30th Apr 2018, 3:31 PM
***
*** - avatar
0
Boem Shakalaka - I won't lie, I don't know how to do that or that you could even do that.
30th Apr 2018, 3:36 PM
ASDFG
ASDFG - avatar
0
Restoring faith - Thank you very much, this solved my issue
1st May 2018, 4:34 AM
ASDFG
ASDFG - avatar