How to do validation for set boolean and double - java

I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double? below is the code i wrote for string.
public class Person
{
private String name;
private String id;
private boolean isNew;
private double bonus
public Person()
{
this("Unknown","unknown",true,0.0);
}
public Person(String id,String name,boolean isNew,double bonus)
{
setId(id);
setName(name);
setIsNew(isNew);
setBonus(bonus);
}
public getId()
{
return id;
}
public getName()
{
return name;
}
public setId()
{
this.id = id;
}
public setName()
{
this.name = name;
}
public void display()
{
System.out.println("Id:" + id);
System.out.printoutln("Name:" + name);
}
// setter validation for string
public void setName(String name)
{
if(name == null)
{
throw new IllegalArgumentException("A valid name must be provided ");
}
name = name.trim();
if(name.length() ==0)
{
throw new IllegalArgumentException("Name must not be blank ");
}
this.name = name;
}
// setter validation for id
public void setId(String id)
{
if(id == null)
{
throw new IllegalArgumentException("A valid id must be provided ");
}
id = id.trim();
if(id.length() ==0)
{
throw new IllegalArgumentException("Id must not be blank ");
}
this.id = id;
}
}
I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double?

When you want return value you have to declare returned type for example "public String getId()" instead "public getId()".
Setter expects a parameter. Example: "public setId(String id)".
All args constructor should looks like:
public Person(String name, String id, boolean isNew, double bonus) {this.name = name; this.id = id;this.isNew = is;this.bonus = bonus; }
For boolean argument constructor expect value. If you want validate something you can change type to Boolean and handle NullPointerExeption.
Or create custom exception:
public class MyWrongBooleanException extends RuntimeException
{
public IncorrectFileExtensionException(String errorMessage, Throwable err)
{
super(errorMessage, err);
}
}

Related

How to use boolean with constructor in java?

We have an activity that will store and display the information of an employee.
I've already created no-modifier class named Person and a public class named Employee which is the the main method. My problem is I don't know how to make the boolean in the class Person which will be used in the main method with a scanner.
class Person {
private String name;
private int contactNum;
private boolean status;
public boolean isRegular;
public String getName(){
return name;
}
public int getContactNum(){
return contactNum;
}
public void setName(String name){
this.name=name;
}
public void setContactNum(int contactNum){
this.contactNum=contactNum;
//how to make the boolean of status and isRegular?
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person P = new Person();
System.out.println("Type employee's name, contact number");
System.out.println("Press Enter after every input");
P.setName(input.nextLine());
P.setContactNum(input.nextInt());
System.out.println("Press Y if employee is regular or N if not");
//how to use boolean here that comes from the class Person?
System.out.println("Name: "+ P.getName());
System.out.println("Contact Number: "+ P.getContactNum());
System.out.println("Status:" + this is where the user is ask to Press Y if employee is regular or N if not )//the status is if the employee is regular or not.
My suggestion for your code:
System.out.println("Press Y if employee is regular or any other key if not");
P.setRegular(input.nextLine().equalsIgnoreCase("Y"));
Your constructor
public class Person {
private String name;
private int contactNum;
private boolean status;
private boolean isRegular;
//No arg constructor
public Person() {
}
//Full arg constructor
public Person(String name, int contactNum, boolean status, boolean isRegular) {
this.name = name;
this.contactNum = contactNum;
this.status = status;
this.isRegular = isRegular;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getContactNum() {
return contactNum;
}
public void setContactNum(int contactNum) {
this.contactNum = contactNum;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public boolean isRegular() {
return isRegular;
}
public void setRegular(boolean regular) {
isRegular = regular;
}
}
Edit
I've noticed an error in the above code and fixed it. This line should be:
P.setRegular(input.next().equalsIgnoreCase("Y"));
You can print booleans as is just like any other Java primitive. `
System.out.println("Status:" + P.isRegular());
would print Status: true or Status: false.
If you want it to print Status: Yes or Status: No, you could do something like this:
System.out.println("Status: ".concat((P.isRegular())?("Yes"):("No")));

Iterating over genric enum instance

As you can see below, I have three declared enums, and each class has a method called getEnumByName() which revives a name and returns the enum which has that name.
I have noticed that I am duplicating the same functionality of this method on each enum.
Is there any way to change this method to a generic one, which receives the given enum's type and does the same logic?
public class Enums {
public enum A {
APPLY("Apply", "abcde");
private String id;
private String name;
A(String name, String id) {
this.name = name;
this.id = id;
}
public static A getEnumByName(String name) throws Exception {
for (A instance : A.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
public enum B {
APPLY("Apply", "1"),
SAVE("Save", "2"),
REVERT("Revert", "2"),
REVERT_CHILD("Revert->Revert", "4"),
REVERT_APPLY("Revert->Revert Apply", "5"),
SYNC("Sync", "6"),
OPERATIONS("Operations", "7"),
IMPORT("Import", "8"),
EXPORT("Export", "9"),
DIFF("Diff", "10");
private String id;
private String name;
B(String name, String id) {
this.name = name;
this.id = id;
}
public static B getEnumByName(String name) throws Exception {
for (B instance : B.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
public enum C {
UPDATE_POLICES("Update Policies", "A"),
OPERATIONS("Operations", "B"),
IMPORT_CONFIGURATION_FILE("Import Configuration File", "c"),
EXPORT_CONFIGURATION_FILE("Export Configuration File", "d"),
EXPORT_LOG_SUPPORT_FILE("Export Log Support File", "f"),
EXPORT_TECHNICAL_SUPPORT_FILE("Export Technical Support File", "g"),
UPDATE_SOFTWARE_VERSION("Update Software Version", "g"),
UPDATE_SECURITY_SINGAUTES("Update Security Signatures", "h"),
DIFF("Diff", "k");
private String id;
private String name;
C(String name, String id) {
this.name = name;
this.id = id;
}
public static C getEnumByName(String name) throws Exception {
for (C instance : C.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
}
One option is to have them all implement a common interface called, say, Named:
interface Named {
String getName();
}
Now you can create a generic method like this:
static <E extends Enum<E> & Named> E getEnumByName(Class<E> enumClass, String name) throws Exception {
return Arrays.stream(enumClass.getEnumConstants())
.filter(e -> e.getName().equals(name))
.findAny()
.orElseThrow(() -> new Exception("There is no operations matches :" + name));
}
And call it like this:
A a = getEnumByName(A.class, "Apply");
Consider using the static Enum valueOf() method. You can call it generically as follows or just call it directly. See this answer for details.
static <E extends Enum<E>> E getEnumByName(Class<E> enumClass, String name) {
return Enum.valueOf(enumClass, name);
}

Convert Object to String

I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.

Is validating fields in both constructor and setter considered bad redundant code?

I have the following class :
public class Project {
private int id;
private String name;
public Project(int id, String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.name = name;
this.id = id;
}
private Project(){}
public int getId() {
return id;
}
public void setId(int id) {
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.id = id;
}
public String getName()
return name;
}
public void setName(String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
this.name = name;
}
}
If you noticed that setName and setId share the same validation for its fields with the constructor. Is this redundant code that could cause issues in the future ( for example if somebody edit the the setter to allow 0 for the id and prevent -1 instead but didn't change the constructor) ? . Should I use a private method to do the check and share it between the constructor and the setter which seems too much if there's a lot of fields.
Note: This is why im not using the setters in the constructor. https://stackoverflow.com/a/4893604/302707
Here is the revised code:
public class Project {
private int id;
private String name;
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
checkId(id);
checkName(name);
//Insted of lines above you can call setters too.
this.name = name;
this.id = id;
}
private Project(){}
public int getId() {
return id;
}
public void setId(int id) {
checkId(id);
this.id = id;
}
public String getName()
return name;
}
public void setName(String name) {
checkName(name);
this.name = name;
}
private void checkId(int id){
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
}
private void checkName(String name){
if(name == null ){
throw new NullPointerException("Name can't be null");
}
}
}
I recommend that you should define one method per field as isValid() and then call the same method in you setter as well as Constructor.
I would say yes. Rather than that, just call the setters from your constructor:
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
setName(name);
setId(id);
// other stuff with creationDate, fps and frames?
}
Also, you shouldn't check for a null name in getName -- do it in setName. Otherwise, bugs are going to be hard to track down -- you want to catch the invalid name as soon as it comes in, not when it's used (which may be much later).
if you make Project immutable, it will eliminate the redundant code. but for now, i think explicitly throwing exceptions in both the constructor and mutator methods is fine.
and i would not call the mutator methods within the constructor for many reasons, including this. also, i would remove the validation code in the accessor method...it's not necessary.

Java access enum field from outside

How I can access the Name field?
public class Animals {
public enum animal{
a1("CAT", 4),
a2("DOG", 4);
}
String Name;
int E;
public animal(String Name, int E){
this.Name = Name;
this.E = E;
}
}
This can be done, but you have a number of syntax errors. The key is to provide getter methods for the enum member variables.
public enum Animal {
a1("CAT", 4), a2("DOG", 4);
private String Name;
private int E;
private animal(String Name, int E)
{
this.Name = Name;
this.E = E;
}
public String getName() {
return Name;
}
public int getE() {
return E;
}
}
You could then access these values anywhere in the rest of your program.
Animal.a1.getName();
Assuming you have an inner enum like this:
public class Animals {
public enum Animal {
a1("CAT", 4), a2("DOG", 4);
final String Name;
final int E;
private Animal(String Name, int E) {
this.Name = Name;
this.E = E;
}
public String getName() {
return Name;
}
}
}
You can get the name using (field so no parenthesis)
Animals.Animal.a1.Name
but better to make all fields private and use the getter:
Animals.Animal.a1.getName()
If I understand correctly, I believe the OP is asking:
“Given a string, "a1", return an object of type Animal with the value Animal.a1”
… in which case, the method you're looking for would be Enum.valueOf(Class,String)
String enumName = "a1";
Animal a = Enum.valueOf (Animal.class (enumName));
if (null == a) {
// error handler …
} else {
// do something interesting with “a”
}

Categories