I spend the last hour doing trial and error with this problem with no avail. We have to, using general coding guidelines (like scan.nextDouble) instead of actual numbers, find the max of a certain number of double values. The only catch is that we can only add code at a certain point. (where the ... is)
double value, valMax;
int n;
n = scan.nextInt();
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
...
}
Where the first value read in is an int and that is the amount of doubles to be entered.
It is difficult because I have to find a way to initialize valMax inside the loop without messing up anything else.
This is what I have been working with, but with nothing working for me.
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
if(j == 0)
{
valMax = scan.nextDouble();
j++;
}
else
{
continue;
}
if(value >= valM开发者_开发问答ax)
{
valMax = value;
}
}
Example input:
5 -4.7 -9.2 -3.1 -8.6 -5.0
Where -3.1 is the max and 5 is the count of following numbers.
Your code seems like a good start.
To help solve your problem, consider:
- Why did you put in the extra
j++
? Do you really need it? (Hint: no ;-) ) - What will the loop do for
j>0
(i.e. after the first iteration)?
That should quickly give you a working solution.
Are you allowed to set the valMax
before the loop? Because in that case you can just do
valMax = Double.MIN_VALUE
and just forget about strange things by doing a normal comparison value > valMax
.
If you are not your approach is how you should do but two things:
- you shouldn't care about incrementing with
j++
since thefor
loop will care about it by itself.. - having a
else { continue; }
will make the body of thefor
jump to next iteration without caring about code that is after the continue. Are you sure that is what you want to do?
I think that you can initialize to Double.MIN_VALUE
at first iteration (j == 0
) and just behave normally afterwards: the only thing you need is that valMax
is initialized before the first comparison with value, not before the scan from stdin..
精彩评论