J'ai écrit un programme court pour un de mes cours et il y a quelque chose que je ne peux pas comprendre. Je suis donc supposé écrire 100 entiers aléatoires sur un fichier, relire les données et imprimer les entiers dans l'ordre croissant. Tout fonctionne bien, mais je ne vois pas ma liste triée finale sur le fichier de sortie, tout le monde peut voir pourquoi?Entrée/Sortie sur un fichier
Voici mon code:
private final static int NUMBEROFRANDOM = 100;
public static void main(String[] args) throws IOException {
// Creating my file
java.io.File file = new java.io.File("Question1.txt");
// If it already exists, print a message and terminate program
if (file.exists()) {
System.out.println("File already exists.");
System.exit(0);
}
// Creating my PrintWriter object
PrintWriter output = new PrintWriter(file);
// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
int number = (int) (Math.random() * 101);
output.print(number + " ");
}
// Creating my Scanner object
Scanner input = new Scanner(file);
// Creating my array list to store the sorted list of 100 elements
ArrayList<Integer> sortedList = new ArrayList<Integer>();
// Reading the elements from the file and adding them into my array list
while (input.hasNext()) {
sortedList.add(input.nextInt());
}
//Sorting elements from array list
Collections.sort(sortedList);
// Printing the elements in increasing order
for (int i = 0; i < sortedList.size(); i++) {
//System.out.println(sortedList.get(i));
output.print(sortedList.get(i));
}
// Closing my objects
input.close();
output.close();
}
Merci beaucoup, toute aide est très appréciée!
Vous devez fermer la sortie après avoir créé les nombres. – notyou
Je vois quelqu'un me battre - ma machine a passé trop de temps à ouvrir mon IDE :) – notyou