i have a problem about my program. The goal of the program is;
- Create a new file
- Create 100 random integer number and write those to created file. Numbers must be seperated by spaces in the file.
- 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();
}
}