Are there any errors or suggestions to improve this code: import java.io.Buffere
ID: 3834828 • Letter: A
Question
Are there any errors or suggestions to improve this code: import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ColorReader { public static int counter = 0; public static void main(String[] args) { BufferedReader colorsReader = null; try { // Define String String colorString; // Use Buffered and FileReader to read .txt file colorsReader = new BufferedReader(new FileReader("Colors.txt")); System.out.println("The colors are: "); // While loop to read each line while ((colorString = colorsReader.readLine()) !=null) { System.out.println(colorString); counter++; } System.out.println(counter + " data values were read."); } catch (IOException e) { e.printStackTrace(); // Close streams } finally { try { if (colorsReader != null) colorsReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
Explanation / Answer
Code is good. I formatted the code and ran the program
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class ColorReader {
public static int counter = 0;
public static void main(String[] args) {
BufferedReader colorsReader = null;
try {
// Define String
String colorString;
// Use Buffered and FileReader to read .txt file
colorsReader = new BufferedReader(new FileReader("P:/Colors.txt"));
System.out.println("The colors are: "); // While loop to read each line
while ((colorString = colorsReader.readLine()) != null) {
System.out.println(colorString);
counter++;
}
System.out.println(counter + " data values were read.");
} catch (IOException e) {
e.printStackTrace();
// Close streams
} finally {
try {
if (colorsReader != null) {
colorsReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OUTPUT :
The colors are:
red
green
blue
yellow
orange
5 data values were read.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.