Jump to content

what is the problem of my code?

buklu

public class SimpleClass {
    public int data;
    public SimpleClass(int d) {
        if(d>0)
            data=d;
        else
            data =0;
    }
}
 

 

 


public class SimpleClassTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SimpleClass myClass=new SimpleClass(10);
        System.out.println(myClass.data);
        myClass.data=-5;
        System.out.println(myClass.data);
    }

}
 

Link to comment
Share on other sites

Link to post
Share on other sites

What problem are you having? what output are you currently getting?

 

I would assume your output is "10" followed by "-5" and you are expecting "10" then "0". The reason it is not outputting 0 is because your check for <0 is happening on the constructor, not when you assign the value to data. 

Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, FlappyBoobs said:

What problem are you having? what output are you currently getting?

 

I would assume your output is "10" followed by "-5" and you are expecting "10" then "0". The reason it is not outputting 0 is because your check for <0 is happening on the constructor, not when you assign the value to data. 

so how to rewrite it?

Link to comment
Share on other sites

Link to post
Share on other sites

39 minutes ago, buklu said:

so how to rewrite it?

 

Look into how to create a "property" in your language. It will have the ability to use get and set (or what ever it is called in your language) the get determines what happens when something asks for the value, the set determines what happens when something assigns to the value. In your case adding a check for >0 when someone tries to get the value would work (so if the current value is over 0 it returns the current value otherwise it returns 0). 

Link to comment
Share on other sites

Link to post
Share on other sites

public class SimpleClass
{
    public int data;
    public SimpleClass(int d) 
    {
        SetData(d);
    }
    public void SetData(int d)
    {
        data = max(0, d); 
    }
}

 

then

 

public class SimpleClassTest
{
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        SimpleClass myClass = new SimpleClass(10);
      
        // will print 10
        System.out.println(myClass.data);
        
        // try set to -5
        myClass.SetData(-5);
        
        // will print 0
        System.out.println(myClass.data);
    }
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×