programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

K&B chapter 7-Question 6 (SCJP 1.4)

Ranch Hand
Posts: 49
• Number of slices to send:
Optional 'thank-you' note:
Can anyone please explain this. I am little confused with Math.round(values[x]+.5), as Math.round() does not take any argument, it is explained in answers but still it is not clear to me.

Thanks
Sandip

Sandip Kaviman
Ranch Hand
Posts: 49
• Number of slices to send:
Optional 'thank-you' note:
It Seems like ranchers are on Ester vacation
[ March 20, 2008: Message edited by: Sandip Kaviman ]

Greenhorn
Posts: 9
• Number of slices to send:
Optional 'thank-you' note:
Math.round is a method which accepts one argument of two different types(double/float).There is no empty parameter method defined for Math.round, Since this method is defined to round up some number, which need to be passed to it.
1) static long round(double a)
Returns the closest long to the argument.
2) static int round(float a)
Returns the closest int to the argument.

In the example, when you are using Math.round(value[x]+0.5) inside the for loop, while iterating through the values array you are just passing values[0] which is -2.3, value[1] which is -1.0 ..values[3] to the Math.round funtion. ( Math.round( -2.3+0.5), Math(-1.0+0.5).....etc

Please try the following to understand the output.

for(int x=0;x<values.length;x++){
long j=Math.round(values[x]+.5);
double k=Math.ceil(values[x]);
System.out.println("j :"+j);
System.out.println("k :"+k);
if(Math.round(values[x]+.5) ==(Math.ceil(values[x]))){
++cnt;
}
}
System.out.println("Same results "+cnt+" times(s)");

output:
j :-2
k :-2.0
j :0
k :-1.0
j :1
k :1.0
j :5
k :4.0
Same results 2 times(s)
( cnt value is updated when j and k values are same, in this case j=-2 and k=-2.0 is same and j=1 and j=1.0 is same)

Sandip Kaviman
Ranch Hand
Posts: 49
• Number of slices to send:
Optional 'thank-you' note:
Thanks Sri,
I just missed to notice signature of round().