Can't get the try-catch-finally block to work - java

I have struggled a long time to get the try-catch-finally block to work. I'm a beginner in java, and are currently learning how to read/write/handle exceptions. In my task I'm trying to read from two separate .txt files. One has countries and population, the other has countries and the area of the country. This is further printed out to a new file where information about countries and area per person is displayed.
I'm not sure if I really can put the finally inside a try-catch block.
Currently I'm getting the error message "Unhandled FileNotFoundException etc.". I've been trying this for for a long time now, and just can't get it to work properly.
private String country;
private double value;
Scanner in1 = new Scanner(new File("countryPopulation.txt"));
Scanner in2 = new Scanner(new File("countryArea.txt"));
PrintWriter out = new PrintWriter("countryAreaPerInhabitant");
public IOAndExceptionHandling(String line) {
int i = 0;
while (!Character.isDigit(line.charAt(i))) {
i++;
}
this.country = line.substring(0, i - 1).trim();
this.value = Double.parseDouble(line.substring(i).trim());
}
public String getCountry() {
return this.country;
}
public double getValue() {
return this.value;
}
public void printAreaPerPerson() {
try {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
}
finally {
in1.close();
in2.close();
out.close();
}
}
catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
}
catch (IOException e) {
e.printStackTrace();
}
}
Thanks! :)

The finally block goes after the catch blocks. It will execute regardless of an exception being thrown or successful completion of the block.
Scanner in1; //field declaration with no assignment
Scanner in2; //field declaration with no assignmetn
/* Omitted Class declaration & other code */
try {
in1 = new Scanner(new File("countryPopulation.txt")); //these require FNF to be caught
in2 = new Scanner(new File("countryArea.txt"));
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(
in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(
in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
The first rendition of this code was throwing the unhandled exception error because the inner try block did not catch the FileNotFoundException. Even though you had a try...catch wrapping that try block, which did catch the FileNotFoundException, the exception would not propogate upwards through the nested try..catch statements

You are nesting two try catch blocks. The inner one only has try finally, but no catch statements. That's where the FileNotFoundException would occur.
try {
try {
Either remove the outer block and just use one or move the catch statements inside the inner try finally.
Copy paste this
public void printAreaPerPerson() {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
}

Put the finally block out side of your try block.
You don't need the inner try block.

Related

Java while(true) loop never ends without a System.out.println

I have the following code with an ArrayList that is filled in other Java class that is a Thread (this is always filled, I have checked every time), then I have in the Main class the problematic block while(true) and the issue is that never ends if I comment or delete the line System.out.println(IDS.size());
Although are Threads in charge of complete the information I need, I cant show the results until all of them are finished. This is the reason of while(true) block.
public static ArrayList<String> IDS = new ArrayList<String>();
//this arraylist is filled in other classes correctly (each Thread add a element -> 10 in total)
//here is the problem
while (true) {
//if I comment the next system.out.println line
//the loop never ends and never breaks
System.out.println(IDS.size());
if(IDS.size()==10) {
break;
}
}
//when the array is filled with the 10 elements, I show all the info
for (int k = 0; k < impresoras.size(); k++) {
System.out.println(impresoras.get(k).ID);
}
I donĀ“t know why this is happening, can someone helps?
Thanks in advance.
Finally I use the join methods for the Threads to avoid the while true loop.
So only I have to call the next method and then do the System.out.println of my items, that will be printed when all Threads ends their work.
public static ArrayList<MyThread> threadList = new ArrayList<MyThread>();
public static void openFileAndCreateThreads(String fileName) {
String line = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] line_parts = line.split(";");
MyThread t= new MyThread(line_parts[0].trim(), line_parts[1], line_parts[2]);
threadList.add(t);
t.start();
}
for (int j=0;j<threadList.size();j++) {
try {
threadList.get(j).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
}

Why I could not save the contents of a file after reading it twice?

Already fixed. Thanks for Mas & ruhul for observing my bugs.
I was trying to read a text file twice, named stationary.txt. The contents of the file has three columns such as the amount, the name of product and the total price.
What I am trying to do first is by averaging each product's price by reading line by line. Then I closed the Buffered and then open it again and read. The second reading takes a variable average and compares each product's price line by line. If line 1 is over the average, then write it into dearer.txt, otherwise write it into cheap.txt
Here is the stationary.txt
1 Highlighter 5.99
2 Pen 9.00
3 Eraser 5.00
4 DrawingPin 2.75
5 Highlighter 10.99
6 FountainPen 20.50
7 Pencil 14.50
Below is the source code
import java.util.*;
import java.io.*;
public class Ques {
public static void main(String[] args) throws FileNotFoundException {
double average = 0;
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
File outFilel = new File("dearer.txt");
FileOutputStream outFileStreaml = new FileOutputStream(outFilel);
PrintWriter outStream1 = new PrintWriter(outFileStreaml);
File outFile2 = new File("cheap.txt");
FileOutputStream outFileStream2 = new FileOutputStream(outFile2);
PrintWriter outStream2 = new PrintWriter(outFileStream2);
computeAverage(bufReader, outStream1, outStream2, average);
}
public static void computeAverage(BufferedReader bufReader, PrintWriter outStream1, PrintWriter outStream2, double average) {
String line = "";
double mark = 0;
double sum = 0;
int count = 0;
try {
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
sum += mark;
count++;
}
average = sum / count;
compareMark(outStream1, outStream2, average);
} catch (NumberFormatException | IOException e) {
System.out.println(e);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
public static void compareMark(PrintWriter outStream1, PrintWriter outStream2, double average) throws FileNotFoundException {
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
String line = " ";
double sum = 0;
double mark = 0;
int count = 0;
try {
double ave = (double) Math.round(average * 100) / 100;
System.out.println("another " + ave);
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
if (mark > ave) {
System.out.println("Over");
outStream1.write(line);
} else {
System.out.println("Less");
outStream2.write(line);
}
}
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The source code is perfectly working, just that I received 0 bytes of both files after executing reading twice (first, doing average and last, doing comparison). Why is that? what am I doing wrong here?
Thank you for your kind help.
Your code is not correct and does not compile. But the main flaws are the following:
Your Double.parseDouble(data[2]) shouldn't work with your 4th line of data. Better use Double.parseDouble(data[data.length - 1])
Remove the readLine()-calls in front of the while-loop.
Write the lines including a line separator.
Close the OutStreams
The Data File that you have provided have the columns seperated by a space. As the 2nd Column has data which contains spaces, the convertion of data[2] to double will trigger an exception. Which will make the program to close the buffers and exit.
Use Commas to seperate column data.
Use better exception handling to find exceptions easily.
All you need is to close those output stream. As you are using bufferredWriter and not flushing it after each write you need to close those output-stream. which will write back those lines or datas into the file. Here is an example how you can do it:
Example 1: using flush().
....
outStream1.write(line);
outStream1.flush();
} else {
System.out.println("Less");
outStream2.write(line);
outStream2.flush();
}
Example 2: most efficient (either way you need to close those buffer too like bufReader.close())
...
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
// add try catch.
outStream2.close();
outStream1.close();
if (bufReader != null ... ) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As requested, an example using List
First a class to hold the stationary data, must be completed:
public class Stationary {
private final int id; // or String if desired
private final String name;
private final double mark; // BigDecimal would be better for money
public Stationary(int id, String name, double mark) {
// TODO error checking
this.id = id;
...
}
public int getId() {
return id;
}
... // TODO other getters
// TODO equals, hashCode, toString
}
and to read the file:
public List<Stationary> read(File file) {
List<Stationary> list= new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
// TODO parse line into id, name, mark
list.add(new Stationary(id, name, mark);
}
}
return list;
}
now the list can be used as needed, e.g. average:
List<Stationary> stationaries = read(STATIONARY_FILE);
...
for (Stationary stationary : stationaries) {
sum += stationary.getMark();
count += 1;
}
...
streams not used to keep it simple

Manipulating tokens to deal with variable number of strings on one line

I will try to explain this as much as I can. I am reading scores from a file onto which my form appends lines. The line consists of a date, home team, score, away team, score.
The stats I gather is away wins, home wins and draws.
The following code works perfectly
JButton viewStatsButton = new JButton(new AbstractAction("VIEW STATS")
{
public void actionPerformed( ActionEvent e )
{
int homeScore = 0;
int awayScore = 0;
int homeWins = 0;
int awayWins = 0;
int scoreDraw = 0;
String line = null;
String output;
String matchDay;
#SuppressWarnings("unused")
String homeTeam;
#SuppressWarnings("unused")
String awayTeam;
String file = "scores.dat";
StringTokenizer tokenizer;
FileReader fileReader = null;
try
{
fileReader = new FileReader (file);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
BufferedReader inFile = new BufferedReader (fileReader);
try
{
line = inFile.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
while(line != null)
{
tokenizer = new StringTokenizer(line);
matchDay = tokenizer.nextToken();
homeTeam = tokenizer.nextToken();
try
{
homeScore = Integer.parseInt(tokenizer.nextToken());
}
catch (NumberFormatException exception)
{
System.out.println("Error in input. Line ignored:");
System.out.println(line);
}
awayTeam = tokenizer.nextToken();
try
{
awayScore = Integer.parseInt(tokenizer.nextToken());
}
catch (NumberFormatException exception)
{
System.out.println("Error in input. Line ignored:");
System.out.println(line);
}
if(homeScore > awayScore)
{
homeWins++;
}
else if(awayScore > homeScore)
{
awayWins++;
}
else
{
scoreDraw++;
}
try
{
line = inFile.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
try
{
inFile.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
output = "Home Wins : "+homeWins+"\nAway Wins : "+awayWins+"\nDraws : "+scoreDraw;
JTextArea textArea = new JTextArea();
frame.getContentPane().add(textArea, BorderLayout.CENTER);
textArea.setText(output);
}
});
scorePanel.add(viewStatsButton);
}
The problem does not come to light until the name of team is made out of two strings i.e.Newcastle United. What I had to do was append the two strings together like NewcastleUnited. I have tried to find out the length of the token and if it's less than 3 then i take it and parse it as integer but it seems that even if the next token reference is in an if statement it still moves to the token after it.
I would appreciate any help and guidance.
Try following
Before calling tokenizer.nextToken() check tokenizer.hasMoreTokens() to ensure that there is a token to read
if(tokenizer.hasMoreTokens())
{
x = tokenizer.nextToken();
}
After reading team name(first part) check whether next part is integer if it is, treat it as score, otherwise append it to team name.
homeTeam = tokenizer.nextToken();
String temp = tokenizer.nextToken();
try
{
homeScore = Integer.parseInt(temp);
}
catch(Exception e)
{
//Comes here if temp is not an integer, so temp is second part of name
homeTeam = homeTeam + " "+temp;
homeScore = Integer.parseInt(tokenizer.nextToken());
}
//Whatever the case, if we come here, it means both hometeam and score are assigned.
...........
...........
...........
Don't forgot to check tokenizer.hasMoreTokens() if you are not sure whether there is a token.

Writing Out to Console as Well as to File

I am trying to get the output of my java program to write to a file.
The user inputs some data which should not be included in the file. When the program responds it should output information to the user, as well as write SOLELY the output to a file.
From examples I have begun with this at the top of my driver class:
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;
This code is in every place where I might receive output from the program:
try {
lineFromInput = in.readLine();
FileWrite.write(lineFromInput);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the class its calling is:
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
}
It creates the output file, but thats it. None of the output from the program is written.
I've looked over numerous examples and this seems to be the easiest way to get the ball rolling, although I'm open to any other suggestions.
Thanks!
Each call to write opens and closes the text file. Each time it is opened it is overwritten, so I would expect only the last thing to be written to appear in the file.
I recommend opening the output file from a constructor, and closing it from a close method.
I think it should be InputStremReader with single t in statement below:
static BufferedReader in= new BufferedReader(new OutputtStreamReader(System.in));
static String lineFromOutput;
As
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;
EDIT: This works fine. Please make sure you provide the input through input console. Also please note that it reads and write(overwrite) single line ONLY.
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
public static void main(String[] args){
String lineFromInput;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
lineFromInput = in.readLine();
FileWrite.write(lineFromInput);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT 2: Updated program for multi-line inputs. Its not best way to open and close file each time to write, but I am just trying to make your program work with minor changes. Let me know, if you need suggestion to avoid repeated opening/closing of the output file.
Change Highlights:
Read lines until "exit"(change the word as desired) is received in input
Open the file in append mode.
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt", true), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
public static void main(String[] args){
String lineFromInput = "";
try {
System.out.println("Provide the inputs in any number of lines");
System.out.println("Type \"exit\" in new line when done");
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
while(!"exit".equals(lineFromInput)){
lineFromInput = in.readLine();
FileWrite.write(lineFromInput+System.lineSeparator());
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT3: Your updated program using Scanner to read the inputs:
private static HashMap<Integer, Object> shapes =
new HashMap<Integer, Object>();
static int i = 0;
public static void main(String[] args) {
PrintWriter output = null;
Scanner scanner = new Scanner(System.in);
try {
output = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e1) {
System.err.println("You don't have accress to this file");
System.exit(1);
}
String command = "";
while(!"quit".equalsIgnoreCase(command)){
System.out.println("Enter your Command: ");
command = scanner.next();
if (command.equalsIgnoreCase("create")) {
String type = scanner.next();
if (type.equalsIgnoreCase("line")) {
double length = scanner.nextDouble();
Line l = new Line(length);
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, l);
i++;
}else if (type.equalsIgnoreCase("circle")) {
double radius = scanner.nextDouble();
String color = scanner.next();
Circle c = new Circle(radius, Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, c);
i++;
}else if (type.equals("rectangle")) {
double length = scanner.nextDouble();
double width = scanner.nextDouble();
String color = scanner.next();
Rectangle r = new Rectangle(length, width,
Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, r);
i++;
}else if (type.equals("square")) {
double length = scanner.nextDouble();
String color = scanner.next();
Square s = new Square(length, Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, s);
i++;
}
}else if (command.equals("printbyperimeter")) {
Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
Arrays.sort(shapeArray);
System.out.println("Print in ascending order...");
for (int j = 0; j < shapeArray.length; j++) {
Shape temp = shapeArray[j];
if (temp.getClass().getName().equals("Line")) {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Perimeter: "
+ temp.getPerimeter());
} else {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Color: "
+ ((Colorable) temp).getColor()
+ ", Perimeter: " + temp.getPerimeter());
}
}
}else if (command.equals("printbyarea")) {
Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
System.out.println("Print in random order...");
for (int j = 0; j < shapeArray.length; j++) {
Shape temp = shapeArray[j];
if (!temp.getClass().getName().equals("Line")) {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Color: "
+ ((Colorable) temp).getColor() + ", Area: "
+ ((Areable) temp).getArea());
}
}
}else if (command.equals("quit")) {
scanner.close();
System.exit(0);
}
}
output.close();
}
Try using the code. It works for me. You just need to change the file path to match where you want the output to go. I am using a BufferedWriter here which I believe is preferred.
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromOutput;
try {
lineFromOutput = in.readLine();
FileWrite.write(lineFromOutput);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class FileWrite {
private static void write(String message) throws IOException {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(new File("C:\\Users\\Teresa\\Dropbox\\output.txt")));
//Replace the above line with your path.
out.write(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
}
}

Java Exception Handling?

The following code calculates the average of numbers that are stored in a text file.
I have added some exception handling for "file not found" errors. I need to know how to add another exception for when the data in the text file is not numeric (or not int). I thought about adding multiple catches. Not sure how though?
import java.util.*;
import java.io.*;
public class NumAvg2 {
public static void main(String[] args)
{
int c = 1;
long sum = 0;
String strFileName;
strFileName = args[0];
Scanner scFileData;
try{
scFileData = new Scanner (new File(strFileName));
while (scFileData.hasNext())
{
sum = sum + scFileData.nextInt();
c++;
}
scFileData.close();
System.out.println("Number of integers: " + (c - 1));
System.out.println( "Average = " + (float)sum/(c - 1));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
}
}
}
You can use Java 7's multi catch if you want
try {
...
}
catch (FileNotFoundException|InputMismatchException ex) {
//deal with exception
}
This is a bit cleaner than multiple catches. If either of these exceptions is thrown it is caught in the single catch block
} catch (InputMismatchException e) {
System.out.println("Not integer!");
System.exit(1);
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
}
...
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
} catch (InputMismatchException e) {
// Add stuff into your new exception handling block
}
...
Your IDE may have not complained about this because InputMismatchException is a RuntimeException (unchecked exception), while FileNotFoundException is a regular checked Exception.
Note that Scanner.nextInt also throws an InputMismatchException if the next token isn't an integer.
From the docs:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
InputMismatchException is a RuntimeException, and so can be ignored in a try/catch block, but you can also explicitly handle it:
try
{
// ... Scanner.nextInt
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(1);
}
catch (InputMismatchException e)
{
// ... not an int
}
To catch multiple exceptions, you chain them like so:
public class NumAvg2 {
public static void main(String[] args)
{
int c = 1;
long sum = 0;
String strFileName;
strFileName = args[0];
Scanner scFileData;
try{
scFileData = new Scanner (new File(strFileName));
while (scFileData.hasNext())
{
sum = sum + scFileData.nextInt();
c++;
}
scFileData.close();
System.out.println("Number of integers: " + (c - 1));
System.out.println( "Average = " + (float)sum/(c - 1));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
} catch(InputMismatchException e){
//handle it
}
}
}
} catch (FileNotFoundException | InputMismatchException e) {
e.printStackTrace();
System.exit(1);
}
Where are you converting your data from file to integer?? You should add one try-catch there..
Instead of using the below while loop, where you have to catch the exception for TypeMismatch: -
while (scFileData.hasNext()) {
try {
sum = sum + scFileData.nextInt();
c++;
} catch (InputMismatchException e) {
System.out.println("Invalid Input");
}
}
You can use a variation like the one below: -
while (scFileData.hasNextInt())
{
sum = sum + scFileData.nextInt();
c++;
}
scanner.hasNextInt() will automatically check whether input in integer or not..
Also, as you are declaring your variable outside your try-catch block.. I would suggest not to use a big try-catch block..
Rather you can surround file reading statement around a try-catch (That would be one statement).. Then after a few statements, you can again surround your scanner.nextInt() around another try-catch..
So, I would modify your code like this: -
public class NumAvg2 {
public static void main(String[] args)
{
int c = 1;
long sum = 0;
String strFileName;
strFileName = args[0];
Scanner scFileData;
try{
scFileData = new Scanner (new File(strFileName));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
}
while (true) {
if (scFileData.hasNextInt())
{
sum = sum + scFileData.nextInt();
c++;
break;
} else {
System.out.println("Enter an integr");
}
}
scFileData.close();
System.out.println("Number of integers: " + (c - 1));
System.out.println( "Average = " + (float)sum/(c - 1));
}
}
This way your code becomes more cleaner.. * Just a Suggestion..

Categories