Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 136,424 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,357 people online right now. Registration is fast and FREE... Join Now!




Help with Files? Thanks

 
Reply to this topicStart new topic

Help with Files? Thanks

mse12
14 Oct, 2008 - 02:14 PM
Post #1

D.I.C Head
**

Joined: 21 Sep, 2008
Posts: 55

I am attempting to create 100 random numbers between 0 and 99. The numbers should be on only one line and separated by spaces (which is why I used the print() method). I attempt to check my results by opening the new file in a text editor, but instead of getting an output such as...

73 4 66 98 80 7…

(with 100 numbers), I instead only receive one number such as...

56

I can not seem to figure out what I am doing wrong as to why I can't get the loop to repeat 100 times. ANy help would be greatly appreciated.

CODE


public class Numbers {
  public static void main(String[] args) throws Exception {
    // Create a text file
    java.io.File file = new java.io.File("Numbers.txt");
    java.io.PrintWriter output = new java.io.PrintWriter(file);

    // Write formatted output to the file  
    for (int i = 0; i <= 100; i++) {
      int numbers = (int) (Math.random() * 100);
    output.println(numbers + " ");
    // Close the file
    output.close();
  }
}
}



User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Help With Files? Thanks
14 Oct, 2008 - 02:48 PM
Post #2

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,022



Thanked: 81 times
Dream Kudos: 1175
My Contributions
THe problem you have is you keep overwriting the text with the next number in the series (of randomly picked numbers).

I suggest changing this:
CODE
for (int i = 0; i <= 100; i++) {
      int numbers = (int) (Math.random() * 100);
    output.println(numbers + " ");
    // Close the file
    output.close();
  }


To this:
CODE
String op = "";
        for (int i = 0; i <= 100; i++) {
              op += " "+ ((int)(Math.random()*100));
          }
        output.println(op);
        output.close();


Hope that helps.
User is offlineProfile CardPM
+Quote Post

mse12
RE: Help With Files? Thanks
14 Oct, 2008 - 02:58 PM
Post #3

D.I.C Head
**

Joined: 21 Sep, 2008
Posts: 55

yes that helped ALOT! thank you very much!
User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Help With Files? Thanks
14 Oct, 2008 - 02:59 PM
Post #4

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,022



Thanked: 81 times
Dream Kudos: 1175
My Contributions
No problem smile.gif Just glad to have helped.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 01:20PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month