Calling the main for another try after throwing an exception - java

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;
}
}

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) {
}
}
}

Java - "varible name" cannot be resolved to a variable - I cannot find where my error is

I have read the other questions with the same title but none have helped with my issue and nothing online has helped either.
I am new to Java and am trying to get a basic program running but I keep getting the aforementioned error.
Code below.
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
Where it says toggleStringCase(input); is where I am getting the error trying to pass the variable to a function.
Nothing i have read suggests what I might be doing wrong.
I am sure it must be a basic error but could someone please point me in the right direction.
Have I missed some syntax somewhere?
input only has scope in the try block, move the call there. Also, I would prefer a try-with-resources over explicitly closing in with another try block. But, it should be noted that closing in also closes System.in (which is a global variable) and great care should be taken in doing so (since any future attempts to read from System.in will fail)
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
String input = in.readLine();
toggleStringCase(input);
} catch (IOException e) {
e.printStackTrace();
}
You have to move your variable [input] to your scope.
cause you declare it inside a try block, but want to use out of the scope.
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
String input=null;
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
input = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
variable input can't be solved to a variable since you don't have an input variable in the scope of your main method (the scope where you are using the input variable as a parameter of toggleStringCase method). You only have input variable in the scope of your try which means that input variable is only accessible within the try and since you are using input variable outside the try that is why it produces the error.
There are 2 possible ways to fix this:
To fix this you should move your declaration of input variable in the scope of your main method. I have updated your code below:
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
String input = ""; // DECLARE input HERE so that it can be used in the scope of your main method
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
input = in.readLine(); // get the actual input
// The try/catch below are commented out since you can combine it to the try/catch above
// START
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
//try {
// END
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
Or you can move the function call for toggleStringCase inside your try-catch. Refer to the code below.
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine(); // get the actual input
toggleStringCase(input); // MOVE IT HERE
// The try/catch below are commented out since you can combine it to the try/catch above
// START
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
//try {
// END
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// toggleStringCase(input); // was moved inside try-catch
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
classic eg of scope problem. The var input is only accessible inside the try block or what is under the braces {}
Move your toggleStringCase(input); in the try block of input itself
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine();
toggleStringCase(input); // moved
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Or you can declare String input outside try block with some default/init value like
String input = "default value";// moved
try {
input = in.readLine();
toggleStringCase(input);
}

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

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.

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..

How to print diff Msg for same NumberFormatException on diff cause in JAVA?

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) {....

Categories