Results 1 to 5 of 5
- 09-29-2013, 03:41 PM #1
- 09-29-2013, 05:07 PM #2
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: Fomatter
Don't know. But as far as we know, you are making your own assumption that the line shown is the culprit. Perhaps you should show more code and the actual error message or warning.
Regards,
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 09-29-2013, 05:24 PM #3
Re: Fomatter
Java Code:package fileProject; import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.Scanner; import javax.swing.JFileChooser; class CountingCharsWordsLines { public static void main(String[] args) throws FileNotFoundException { int lines = 0, words = 0, characters = 0; JFileChooser fileChooser = new JFileChooser(); File selectedFile = null; if (args.length == 0) { if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } else { System.out.println("No File Selected!"); System.exit(0); } } else { // if first selectedFile = new File(args[0]); if (args.length > 1) System.out.printf("%s%n", "Usage: FileName FileToProcess"); } try (Scanner scanner = new Scanner(selectedFile)) { while (scanner.hasNext()) { String line = scanner.nextLine(); words += line.split(" ").length; characters += line.toCharArray().length; lines++; } } // try scanner Formatter fmt = new Formatter().format("%-10s = %3d %n%-10s = %3d %n%-10s = %3d %n ", "Lines", lines, "Words", words, "Characters", characters); // warning here System.out.print(fmt); fmt.close(); } // main } // class
- 09-29-2013, 06:12 PM #4
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: Fomatter
The problem is you are not invoking your Formatter object in a try with resources block. And the one it is complaining about is not the one you are closing but the anonymous instance you created. So replace lines 40 to 43 with the following:
Java Code:try (Formatter formatter = new Formatter()) { Formatter fmt = formatter.format("%-10s = %3d %n%-10s = %3d %n%-10s = %3d %n ", "Lines", lines, "Words", words, "Characters", characters); System.out.print(fmt); }
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 10-02-2013, 09:27 AM #5
Bookmarks