[英]minimum value method will return a negative number when i have an input validation that should stop negative numbers
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.但是,我有一个用于输入验证的 if 语句,可以阻止用户输入负数。 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.我不确定如何解决这个问题,但我认为它与 scope 有关。
I have tried moving the methods around to different levels of scope.我尝试将这些方法移动到 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();
您首先在这一行添加数组中的数字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:因此,要解决这个问题,首先将输入数字存储在 temp 变量中并进行 -ve 检查,然后像这样添加到数组中:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.