Casting a Throw Exception
Why won't my throw exception work?!?! :@:
DRIVER:
Code:
public class Driver { public static void main(String[] args)
{
//MAIN IS FOR TESTING PURPOSES ONLY
//object created with new class; example of setting age&name + output results
Person me=new Person();
me.setAge(125);
me.setName("Robert");
System.out.println(me.getName() + " is currently " + me.getAge() + " years old.");
//PRINTING THE OBJECT ITSELF
System.out.print(me);
}
}
CLASS:
Code:
public class Person {
//variables that store a Person's weight and age(not directly accessable by client)
private int age;
private String name;
//mutator method that makes sure the person is of valid age. Error otherwise.
public void setAge(int a) throws IllegalArgumentException{
if(a>=1||age<=95)
{
//changes the instance variable based on clients input.
age=a;
}
else
{
throw new IllegalArgumentException("Invalid Age.");
}
}
//mutator method that assigns what the client inputs to the instance variable
public void setName(String n)
{
name=n;
}
//accessor method that returns the values in the corresponding instance variable (the person's age).
public int getAge()
{
return age;
}
//accessor method that returns the values in the corresponding instance variable (the person's name).
public String getName()
{
return name;
}
}
OUTPUT: Robert is 125 years old.
Shouldn't it display an error? (DUE TO MY THROW EXCEPTION :(doh):)
Re: Casting a Throw Exception
if(a>=1||age<=95)
1. why age ? do you mean "a" too here or? :)
2. because the first condition is true 125 >= 1 --> yes, so the second condition is not tested
3. try && instead of || :D
--> if (a >= 1 && a <= 95) {
Re: Casting a Throw Exception
THANK YOU YOUR A GENIUS :D - hits myself -
Last quesiton: when printing the object itself, why does it output: Person@4e82701e
Re: Casting a Throw Exception
When you print an instance of a class you made yourself, it uses the default implementation of toString(), unless you explicity override it, like so:
Code:
class Person{
//constructor(s), field(s), other method(s)
@Override
public String toString(){
//return whatever you want to be printed when you print the object itself
}
}
Re: Casting a Throw Exception
so why did it print out 'Person@4e82701e'
What does toString() do?? where did everything after the @ come from?
Re: Casting a Throw Exception
The thing after the @ is the hexadecimal memory address of the object.