I have a method that determines the minumum value in an array. However, i have an if statement for an input validation that stops the user from entering negative numbers. However, when the user inputs a negative number the minimum value method stores that value when it should ignore it. I am not sure how to solve this, but i think it has something to do with the scope.
I have tried moving the methods around to different levels of scope.
import java.util.*;
public class Rainfall {
public static void main(String[] args) {
// set and intialize vairables
double[] rainfall = new double[12];
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
double totalRainfall = 0;
double averageRainfall = 0;
double max = rainfall[0];
// scanner to get user input
Scanner scanner = new Scanner(System.in);
// for loop to iterate through the months to get user input on rainfall each month
for (int i = 0; i < rainfall.length; i++) {
System.out.println(
"How much rainfall did you recieve, in inches, for the month of: " + months[i]);
rainfall[i] = scanner.nextDouble();
// if statement to reject negative numbers
if (rainfall[i] < 0) {
System.out.println("You can not enter a negative number");
System.out.println("How much rainfall did you receive for the month of: " + months[i]);
rainfall[i] = scanner.nextDouble();
}
// calculate total and average rainfall
totalRainfall = rainfall[i] + totalRainfall;
}
}
}
I need the minimum value method to not store negative numbers.
Replace
if(rainfall[i] < 0)
with
while(rainfall[i] < 0)
This forces the user to input valid rainfalls.
You are adding the number in array first at this line rainfall[i] = scanner.nextDouble();
and then doing the check on negative number. So to resolve this store the input number in temp variable first and do the -ve check and then add into array like this:
Double temp = scanner.nextDouble();
//while statement to reject negative numbers
while (temp < 0) {
System.out.println("You can not enter a negative number");
System.out.println("How much rainfall did you recieve for the month of: " + months[i]);
temp = scanner.nextDouble();
}
rainfall[i] = temp;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.