Home » Java » I need help making a java constructor that akes a string and initilizes the value var with appropriate in-Exceptionshub

I need help making a java constructor that akes a string and initilizes the value var with appropriate in-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

so sorry if my question is dumb but i haven’t done java in 2 years. I’m working in my hw right now and i’m one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:

public  FancyInt(String a) {
       value = "";

       a = this.value;
}

basically this constructor takes a string and initalizes the value to the appropriate int

How to&Answers:

Firstly if you want to equal “value” TO “a”, you must write:

this.value = a;

in Java (and a lot of programming languages), you must write variable that you change before equal mark.

Second, if you will make “value” Integer. You must change it to int first:

try {
   this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Third, if “value” is an Integer. You must define that with numbers:

value = ""; //if value is an Integer, delete this line.

Answer:

If you say that the variable “value” is a Integer, then your code cannot compile because you are assigning a String (in this case, an empty string “”) to a Integer.

According to your last sentence, I think your code should look like this:

public FancyInt(String a) {

     this.value = isInteger(a)? Integer.parseInt(a) : 0;
}

private boolean isInteger(String val) {

    try{
        Integer.parseInt(val);
        return true;
    } 
    catch (NumberFormatException e) {
        return false;
    }
}

You can change the implementation of the isInteger method, in this link Determine if a String is an Integer in Java you have multiple options that could help you.