• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor question

 
Rene Rad
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm studying java and as part of my project I have to create a constructor that initializes 6 instance variables, 2 of them are doubles (2 Strings and 2 ints too) and I need to work in that those two doubles do not go below 0. If one of them is negative it has to set the relevant field to 0. The other numeric fields will be initialized to 0.

I know how to create an if else that will check one field but I'm lost on how to do 2. Belowis what I have so far but it's wrong. Can anyone provide insight?

Thanks.


 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've got a bit of unnecessary redundancy in that code. I recommend that you just modify the single field inside the if block. e.g.,
 
Rene Rad
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, this worked great. I commented this thread into my source code for credit. Home I don't get marks docked but whatever.

Thanks again.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50284
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I suggest you see whether you can reduce those if-elses to a single line with the ?: operator.
 
Rob Spoor
Sheriff
Pie
Posts: 20671
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or in this case simply use Math.max.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50284
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course, Math.max uses ?: in the implementations I have seen.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic