Here's my current code:
import java.lang.String;
import java.io.*;
class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
super("The age you entered is not between 0 and 125");
}
}
public class questionOne
{
public static void main(String args[])
{
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try
{
name = br.readLine();
}
catch(IOException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try
{
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
finally
{
System.out.println("No errors found.");
}
}
}
The assignment is to write a program that asks for the user's name and age, and if the age is not between 0 and 125 throw an exception. I'm getting two errors in my code:
questionOne.java:31: variable name might not have been initialized
System.out.println("Hello " + name + ", how old are you?");
^
questionOne.java:46: exception InvalidAgeException is never thrown in body of corresponding try statement
catch(InvalidAgeException e)
^
2 errors
I'm not sure how to fix them.
Your first error is cause by never initializing name. Keep in mind that its only initialized within the Try Catch block, which causes the compiler to throw an error since it may never be initialized within the program. So altering your line above the try catch block to
String name = "";
Will resolve that error.
Edit:
This might be what you need to do outside of the try catch block.
if (age < 0 || age > 125){
throw new InvalidAgeException();
}
questionOne.java:31: variable name might not have been initialized
System.out.println("Hello " + name + ", how old are you?");
It is because variables inside the function needs to be initialized before using it. When you try to use uninitialized variables inside a function, compiler throws an exception.
So, try using this
String name = " ";
questionOne.java:46: exception InvalidAgeException is never thrown in body of corresponding try statement
catch(InvalidAgeException e)
You have not thrown InvalidAgeException anywhere ( and so the compiler is complaining).
Try this,
if (age < 0 || age > 125){
throw new InvalidAgeException("This is an invalid age :" + age);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With