122k views
3 votes
Objectives:

In this lab, the following topic will be covered:

Text I/O
Task

Given the text file "unsortedStudents.txt" that has IDs of students in a course, write a program that creates a new text file "sortedStudents.txt" in which the students are sorted by IDs in an increasing order. The first line of both text files has the number of students in the course.

Note:

Use only File, PrintWriter, and Scanner classes.

unsortedStudents.txt

10
201962660
201930180
201953700
201901460
201925220
201973190
201945440
201965470
201994720
201983290

1 Answer

2 votes

Final answer:

To sort the students' IDs in increasing order from a text file, you can use the File, PrintWriter, and Scanner classes. Read the contents of the file, store the IDs in an ArrayList, sort the ArrayList, and write the sorted IDs to a new file.

Step-by-step explanation:

In order to sort the students by their IDs in increasing order, you can follow these steps:

  1. Read the contents of the 'unsortedStudents.txt' file using the File and Scanner classes.
  2. Create an ArrayList to store the IDs of the students.
  3. While reading the file, add each ID to the ArrayList.
  4. Use the Collections class to sort the ArrayList in increasing order.
  5. Create a PrintWriter object to write the sorted IDs to the 'sortedStudents.txt' file.
  6. Write the number of students, followed by the sorted IDs, to the file.
  7. Close the PrintWriter and Scanner objects to release system resources.

Here's a sample code snippet to illustrate the steps:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class StudentSorter {

public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("unsortedStudents.txt");
Scanner scanner = new Scanner(inputFile);
ArrayList studentIDs = new ArrayList<>();

// Read student IDs from input file
while (scanner.hasNextInt()) {
int id = scanner.nextInt();
studentIDs.add(id);
}

// Sort the student IDs
Collections.sort(studentIDs);

File outputFile = new File("sortedStudents.txt");
PrintWriter writer = new PrintWriter(outputFile);

// Write the number of students
writer.println(studentIDs.size());

// Write the sorted student IDs
for (int id : studentIDs) {
writer.println(id);
}

// Close the writer and scanner
writer.close();
scanner.close();
}
}

User Ignat
by
8.2k points