October 9, 2012

Positive integer data type in java

Question by user1724891

I want to make a code where I can only accept positive integers, how would you recommend to do this?

I was thinking to set the Constructor int mySddads = 0 then writing in the accessor an if condition that if the value entered was less than 0, then it returns a system print out saying error blah blah blah, but was there any better ideas to do this?

Answer by Starx

This should be very simple I think

public setPostiveInt(int i) {
   if(i > 0) {
       this.postiveInt = i; 
   } else {
      //handle error or throw exception
   }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!