I want to implement a programm, which reads two strings from the user input.
try
{
System.out.println( "please enter a valid URL ( i.e. http://www.uibk.ac.at )" );
Scanner inputScanner = new Scanner( System.in );
String urlString = inputScanner.next();
asciiTable = new int[NUM_ASCII_CHAR];
URL url = new URL( urlString );
URLConnection connection = url.openConnection();
connection.connect();
InputStreamReader in = new InputStreamReader( url.openStream() );
countCharactersfromFile( in );
printAsciiTable( asciiTable );
printNumberOfChars( asciiTable );
inputScanner.close();
in.close();
}
// it has not the form of an URL
catch ( MalformedURLException e )
{
e.printStackTrace();
}
// If the site cannot be connected
catch( UnknownHostException e )
{
e.printStackTrace();
}
// some IO-Error occurs
catch ( IOException e )
{
e.printStackTrace();
}
// if the ASCII array is empty
catch( EmptyListException e )
{
e.printStackTrace();
}
catch( IllegalArgumentException e )
{
e.printStackTrace();
}
catch ( Exception e )
{
e.printStackTrace();
}
try
{
System.out.println( "Please enter the name of a file " );
asciiTable = new int[NUM_ASCII_CHAR];
Scanner scanner = new Scanner( System.in );
String fileString = scanner.next();
FileInputStream fileStream = new FileInputStream( fileString );
InputStreamReader in = new InputStreamReader( fileStream );
countCharactersfromFile( in );
printAsciiTable( asciiTable );
printNumberOfChars( asciiTable );
scanner.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
catch( EmptyListException e )
{
e.printStackTrace();
}
catch( IllegalArgumentException e )
{
e.printStackTrace();
}
catch ( Exception e )
{
e.printStackTrace();
}
At first I want to let you know that I know the problem. I should only use 1 Scanner in my program. But if use only one try block in my program, i am not allowed to execute the 2nd part of the task, if an exception is thrown. I have a solution, but I do not know if it is a good one.
try
{
Scanner inputScanner = new Scanner( System.in );
try
{
//the URL code, use inputScanner here
}
catch()
{
}
try
{
// The file code, use inputscanner here
}
catch()
{
}
inputscanner.close();
}
catch()
Is the solution, which is shown above a good one? Or do you have some better solutions for my problem.
Thanks Patrik