编码和尝试创建一个应用程序的新手,该应用程序提示用户输入调查答复并将每个答复输出到文件。使用格式化程序创建一个名为numbers.txt的文件。每个经理应使用方法格式编写。然后在其中修改程序以从numbers.txt中读取调查答复。应该使用扫描仪从文件中读取响应。使用方法nextInt从文件中一次输入一个整数。程序应继续读取响应,直到到达文件末尾。结果应输出到文本文件“ output.txt”。
我尝试了几种不同的方法,并且不断出现资源泄漏。
public class StudentPoll {
public static void main( String[] args ) {
// student response array (more typically, input at runtime)
int[] responses = { 1, 2, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 14 };
int[] frequency = new int[ 6 ]; // array of frequency counters
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ ) {
try {
++frequency[ responses[ answer ] ];
} // end try
catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println( e );
System.out.printf( " responses[%d] = %d\n\n", answer, responses[ answer ] );
} // end catch
} // end for
System.out.printf( "%s%10s\n", "Rating", "Frequency" );
// output each array element's value
for ( int rating = 1; rating < frequency.length; rating++ )
System.out.printf( "%6d%10d\n", rating, frequency[ rating ] );
} // end main
} // end class StudentPoll
/*
java.lang.ArrayIndexOutOfBoundsException: 14
responses[19] = 14
Rating Frequency
1 3
2 4
3 8
4 2
5 2
*/
Tried the below just playing around and get the resource leak
package studentPoll;
//Fig. 7.8: Numbers.java
//Writing data to a sequential text file with class Formatter.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter 14 survey responses and enter each time:",
"Enter end-of-file indicator to end input.");
// open numbers.txt, output data to the file then close numbers.txt
try (Formatter output = new Formatter("numbers.txt")) {
while (input.hasNext()) { // loop until end-of-file indicator
try {
// output new record to file; assumes valid input
output.format("%d %d %d %d %d %d %d %d %d %d %d %d %d %d", input.nextInt(),
input.next(), input.next(), input.nextDouble());
}
catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.print("? ");
}
}
catch (SecurityException | FileNotFoundException |
FormatterClosedException e) {
e.printStackTrace();
System.exit(1); // terminate the program
}
}
}
答案 0 :(得分:0)
Scanner input = new Scanner(System.in);
警告:资源泄漏:“输入”从未关闭
只需在程序结尾处调用input.close();
。