The code that I'm writing has two classes: writeInts and readInts. I wrote writeInts to randomly generate 100 numbers between 0 and 1000 and output them to a data.dat file.
readInts is supposed to open a DataInputStream object and read in the "raw" data from the data.dat file and store the 100 integers in an array. My problem is that I can't seem to read the data correctly. Any help with this would be greatly appreciated. Thanks!
writeInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
int num = 0 + (int)(Math.random());
int[] counts = new int[100];
for(int i=0; i<100; i++) {
output.writeInt(num);
counts[i] += num;
System.out.println(num);
}
output.close();
}
}
readInts:
import java.io.*;
import java.util.*;
public class ReadInts {
public static void main(String[] args) throws IOException {
// call the file to read
Scanner scanner = new Scanner(new File("data.dat"));
int[] data = new int[100];
int i = 0;
while (scanner.hasNextInt()) {
data[i++] = scanner.nextInt();
System.out.println(data[i]);
scanner.close();
}
}
}
If you want to write binary data, use DataInputStream/DataOutputStream. Scanner is for text data and you can't mix it.
WriteInts:
ReadInts:
I'd recommend that you abandon
DataInputStream
andDataOutputStream
.Write the ints one to a line using
FileWriter
and read them using aBufferedReader
, one per line. This is an easy problem.More. If you want to generate a random number in range from 0 to 1000 (both inclusive), you use this statement:
It works that way: Math.random() generates a double in range from 0 to 1 (exclusive), which you then should map to integer range and floor. If you want you maximal value to be 1000, you multiply it by 1001 - 1001 itself is excluded.
Yep, like that: