1

i have a problem about my program. The goal of the program is;

  1. Create a new file
  2. Create 100 random integer number and write those to created file. Numbers must be seperated by spaces in the file.
  3. Read the data back from the file and display the data.

Actually, i have completed first and second parts. In fact, i've written the third part but it returns just 0 value 100 times. It doesnt read the values which the file contains.

Btw the program should create new file and read related file in same execution.

Could you help me?

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;


public class Task3 {

public static void main(String[] args) throws IOException {
    String home = System.getProperty("user.home");
    File file = new File(home + File.separator + "Desktop" + File.separator + "Example.txt");

    if(file.exists()) {
        System.out.println("File already exists");
        file.delete();
        file.createNewFile();
    }

    PrintWriter output = new PrintWriter(file);
    Random random = new Random();

    for (int i = 0; i <= 100 ; i++) {
        output.print(random.nextInt(100) + " ");
        if(i == 99) output.print(random.nextInt(100));
    }

    Scanner readFile = new Scanner(file);
    readFile.useDelimiter("\\s");

    int [] readRandomNumbers = new int [100];
    int i = 0;
    while(readFile.hasNextInt()){
        readRandomNumbers[i++] = readFile.nextInt();
    }

    for (int j = 0; j < readRandomNumbers.length; j++) {
        System.out.println(readRandomNumbers[j]);
    }
    output.close();
}
}
2
  • 1
    flush/close your output stream before reading from file. Commented Dec 23, 2019 at 13:35
  • Also if you are working with Java-7 or above you can make use of try-with-resources which takes care of closing your streams, safely Commented Dec 23, 2019 at 13:37

1 Answer 1

2

You just have to flush the writer, and in the loop i < 100 and not i <= 100

for (int i = 0; i < 100 ; i++) {
    output.print(random.nextInt(100) + " ");
}
output.flush();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.