Reputation: 75
I am trying to determine if each input a user provides is the max
or min
out of all of their inputs, and then assign that input to a variable high
or low
int inputnum = 0;
double sum = 0;
double lastinput = 0;
double high;
double low;
double average;
Scanner input = new Scanner(System.in);
high = 0;
low = 0;
do {
System.out.println("Enter a number. Type 0 to quit.");
lastinput = input.nextDouble(); //reads input
sum += lastinput; //add to sum
if (lastinput != 0) {
inputnum += 1; //counts number of inputs (except 0)
}
if (lastinput > high && lastinput != 0) {
high = lastinput;
}
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
average = (sum / inputnum);
} while (lastinput !=0); //repeat unless user inputs 0
The problem is that I cannot declare the variable without assigning it a value (for example 0). If a user inputs 3
, 5
, and 7
for example, the low
value is still defined as 0
.
Upvotes: 3
Views: 84
Reputation: 14628
The value of low
and high
can be initialed by your first input before your loop.
Upvotes: 0
Reputation: 6151
That's because you intialize low
to zero, and all the values you enter are bigger, so it will never be updated. You have to assign it to the highest possible value - low = Double.MAX_VALUE;
so all the other values will be lower than it.
Similarly, you should initialize high as
high = Double.MIN_VALUE;
Upvotes: 2
Reputation: 1035
The problem is with your following condition:
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
Notice that the variable low
is 0 initially. So if your actual minimum is higher than 0, then it will not affect the value of low
because it is 0. There can be several logical solutions to this:
Use a sentinel value : Initialise low with the highest possible value of double so that the user input is always lower, therefore affects the value of low
double low = Double.MAX_VALUE;
Change the if condition : You could change the if
condition to account for the fact that the initial value is 0.
if (low==0 || (lastinput < low && lastinput != 0)) {
low = lastinput;
}
Upvotes: 2
Reputation: 31888
You should use a maximum value for low
by default or else the condition lastinput < low
for non-negative inputs would always be false
and 0 remains as your output.
double low = Double.MAX_VALUE;
Upvotes: 1