Objectives: To practice File and text input output concept 1. (Process scores in a text file) Suppose a text file contains an unspecified number of scores separated by spaces. Write a program that prompts the user to enter the file, reads the scores from the file, and displays their total and average. 2. (Write/read data) Write a program to create a file named Lab07_02.txt if it does not exist. Write 100 integers created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display the data in increasing order. 用JAVA解答
时间: 2023-12-03 16:43:18 浏览: 94
Woollams, S., & Brown, M. Transactional analysis: A modern and comprehensive text of TA theory and practice. Dexter, MI: Huron Valley Institute, 1978, xiv + 295 pp., [dollar]15.00
1.
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ProcessScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = input.nextLine();
File file = new File(fileName);
try {
Scanner fileInput = new Scanner(file);
int total = 0;
int count = 0;
while (fileInput.hasNextInt()) {
total += fileInput.nextInt();
count++;
}
double average = (double) total / count;
System.out.println("Total: " + total);
System.out.println("Average: " + average);
fileInput.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
input.close();
}
}
```
2.
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class WriteReadData {
public static void main(String[] args) {
File file = new File("Lab07_02.txt");
try {
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < 100; i++) {
output.print((int) (Math.random() * 100) + " ");
}
output.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
try {
Scanner input = new Scanner(file);
int[] numbers = new int[100];
int index = 0;
while (input.hasNextInt()) {
numbers[index] = input.nextInt();
index++;
}
Arrays.sort(numbers);
for (int number : numbers) {
System.out.print(number + " ");
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}
```
阅读全文