Reputation: 59
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 >= valMax)
{
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.
Upvotes: 1
Views: 327
Reputation: 133669
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:
j++
since the for
loop will care about it by itself..else { continue; }
will make the body of the for
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..
Upvotes: 0
Reputation: 83645
Your code seems like a good start.
To help solve your problem, consider:
j++
? Do you really need it? (Hint: no ;-) )j>0
(i.e. after the first iteration)?That should quickly give you a working solution.
Upvotes: 1