Ich schrieb ein kurzes Programm für eine meiner Klasse und es gibt etwas, das ich einfach nicht herausfinden kann. Also soll ich 100 zufällige Ganzzahlen in eine Datei schreiben, die Daten zurücklesen und die Ganzzahlen in aufsteigender Reihenfolge ausgeben. Alles funktioniert gut, aber ich sehe meine endgültige sortierte Liste nicht in der Ausgabedatei, jeder kann sehen warum?Eingabe/Ausgabe für eine Datei
Hier ist mein 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();
}
Vielen Dank, ist jede Hilfe sehr geschätzt!
Sie müssen die Ausgabe schließen, nachdem Sie die Zahlen erstellen. – notyou
Ich sehe, jemand schlug mich dazu - meine Maschine verbrachte zu lange meine IDE öffnen :) – notyou