mardi 16 février 2016

Why is the smallest number read from my file always 0? (Java)

When I run the program, the smallest number always turns out to be 0. Why is this? The largest and average values seem to be correct.

The problem most likely lies in how I am using the random class. Thanks for your help guys.

import java.io.*;
import java.util.*;
import java.util.Arrays;

public class ReadAndWrite {
public static void main(String[] args) {
    Random ran = new Random();
    int i_data = 0;
    int[] sort = new int[100];
    File file = new File("Test4");
    int total = 0;
    int average = 0;    

    try {
    file.createNewFile();
    }       
    catch(Exception e) {
        System.out.println("Could not create the file for some reason. Try again.");
        System.exit(0);
    }

    try {
        FileOutputStream fos = new FileOutputStream("Test4");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        for(int i = 0; i <= 100; i++) {
          int x = ran.nextInt(100);
          oos.writeInt(x);
        }
        oos.close();
    }
    catch(IOException e) {
        System.out.println("Whoops");
    }

    try {           
        FileInputStream fos = new FileInputStream("Test4");
        ObjectInputStream ooss = new ObjectInputStream(fos);            

        for (int i = 0; i < 100; i++) {
            sort[i] = ooss.readInt();

        }
        Arrays.sort(sort);
        for(int i = 0; i < 100; i++) {
            total = total + sort[i];
            average = total/100;
        }


        System.out.println("The largest number in the file is: " + sort[99]);
        System.out.println("The smallest number in the file is: " + sort[0]);
        System.out.println("The average number in the file is: " + average);

        ooss.close();
    }
    catch(Exception e) {
        System.out.println(e);
    }   
  }
}




Aucun commentaire:

Enregistrer un commentaire