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..
Related
Can any one help in writing a logic in executing the line after the exception line. In the code I caught the exception but I want to print line ""This will not be printed"" after exception was caught from the same place.
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
bool mExceptionOccur = false;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
mExceptionOccur = true;
System.out.println("Division by zero.");
}finally{
if (mExceptionOccur)
System.out.println("After catch statement. Exception Occurred");
else
System.out.println("After catch statement. No Exception Occurred");
}
Use a try-catch-finally statement. The finally part will always be executed irregardless whether an exception is caught or not.
By adding a variable , you can monitor if an exception have been thrown prior to the executing the finally part.
what about this:
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
System.out.println("This will not be printed.");
d = 0;
a = 42 / d;
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
I want to restart the program after throwing an exception this my code
System.out.println("please enter an intger to compute its factorial:");
BufferedReader bufferedreader = new BufferedReader( new InputStreamReader(System.in));
String number ="";
try {
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("error you should enter a number");
throw new MyExceptions("try again please use integer numbers");
//if possible to restart the main
}
so when ever the user enters a character the program will throws an exception and then restarts is this possible??
In general, one should not be invoking main recursively, especially for the purpose of restarting the program.
If you want to go back to a certain point in your program, use a loop. Here is one example of how you can do it:
boolean done = false;
do {
done = true;
try {
...
} catch (NumberFormatException e) {
System.out.println("error you should enter a number");
done = false;
}
} while (!done);
The loop will continue from the beginning each time the exception handler sets done to false.
You could just put it in a loop.
While(isValid != TRUE)
{
try
{
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
isValid = TRUE;
}
}
catch (NumberFormatException e)
{
System.out.println("error you should enter a number");
System.out.println("try again please use integer numbers");
isValid = FALSE;
}
}
I am trying to make a scoring system for a game I'm writing, but I need to be able to read an integer variable from a text document. I can easily get a String variable, but it won't come in as an integer. How would I go about doing that? Here is the code I have for reading and writing the score, but the input won't come in as an integer, as you can see when the println outputs the value of score2 integer. Thanks! I'm using an eclipse IDE for Java by the way.
import java.io.*;
public class ClassName {
public static void main(String[] args) {
FileOutputStream output;
FileInputStream input;
in score = 10;
int integer = 4;
try {
output = new FileOutputStream("score.txt");
new PrintStream(output).println(score);
output.close();
} catch (IOException e) {}
try {
input = new FileInputStream ("score.txt");
int score2 = (new DataInputStream(score).readLine());
input.close();
System.out.println(score2);
} catch (IOException e) {}
}
}
}
I would use a Scanner and try-with-resources,
try (Scanner sc = new Scanner(new File("score.txt"))) {
int score2 = sc.nextInt();
System.out.println(score2);
} catch (IOException e) {
e.printStackTrace();
}
To convert string to int you can use Integer.parse method
What you want to do is called parsing.
You want to use the parseInt() method of the Integer java class (link to doc)
try{
Integer.parseInt(new DataInputStream(score).readLine())
} catch (NumberFormatException e) {
}
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.
How to print diff Msg for same NumberFormatException on diff cause in JAVA?
try {
int a=Integer.parseInt(aStr);
int b= Integer.parseInt(bStr);
}catch (NumberFormatException ex) {
if ex's cause is from int a;//ex.getCause()=a?
System.out.println("a is not a integer");
if ex's cause is from int b
System.out.println("b is not a integer");
}
try {
final int a = Integer.parseInt(aStr);
} catch (final NumberFormatException ex) {
System.out.println("a is not a integer");
}
try {
final int b = Integer.parseInt(bStr);
} catch (final Exception e) {
System.out.println("b is not a integer");
}
You can declare the variables in two different try catch...
try {
int a=Integer.parseInt(aStr);
}catch (NumberFormatException ex) {
System.out.println("a is not a integer");
}
try{
int b= Integer.parseInt(bStr);
}catch (NumberFormatException ex) {
System.out.println("b is not a integer");
}
Instead of doing that you can keep you try block unchanged and in the catch block print the stack trace by doing this
ex.printStackTrace();
This will give you the line number where the exception occurred which will either be at variable a or b
well it provides nice message still if you want you can have two catch blocks
Another possibility.
Introduce a string variable before the try block:
String msg = "a is not an integer";
try {
// parse a
msg = "b is not an integer";
// parse b
} catch (...) { println(msg); }
The only alternative to two try catch block would be setting a marker
boolean aSet = false;
try{
int a = Integer.parseInt(aStr);
aSet = true;
int b = Integer.parseInt(bStr);
} catch (NumberFormatException ex) {
if (aset) {....