[英]Java: Not adding a negative value
嗨,我的Java作業是:“編寫Java程序來跟蹤植物的生長。” 所以我的問題是植物的Height(h)不能為負,但是我不確定如何使我的程序添加0或不添加任何東西,而不是將“ h”添加為-1
import java.util.Scanner;
public class PlantGrowth {
public static void main(String [] args){
final int NUMMONTHS = 12;
int [] avgTemp = {46, 48, 49, 50, 51, 53, 54, 55, 56, 55, 51, 47};
int [] avgRain = {5, 3, 3, 1, 1, 0, 0, 0, 0, 1, 3, 4};
int [] newGrowth;
newGrowth = new int[NUMMONTHS];
int min_temp, max_temp, min_rain, h = 0;
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the 210 gardening planner!");
System.out.println("Enter minimum temperature for plants:");
min_temp = in.nextInt();
System.out.println("Enter maximum temperature for plant:");
max_temp = in.nextInt();
System.out.println("Enter minimum rainfall for plant:");
min_rain = in.nextInt();
System.out.println("Month\tTemp Rain Growth\tPlant Height");
for (int i = 0; i < NUMMONTHS; i++){ \\i think the problem is somewhere here
if (avgTemp[i] < min_temp || avgTemp[i] > max_temp){
newGrowth[i] = -1;}
else {
newGrowth[i] = avgRain[i] - min_rain;}
h += newGrowth[i];
System.out.printf("%s\t%s%4s%5s\t\t%s\n", i, avgTemp[i],
avgRain[i], newGrowth[i], h);
}
}
}
\\This is my output
Enter minimum temperature for plants:
47
Enter maximum temperature for plant:
60
Enter minimum rainfall for plant:
0
Month Temp Rain Growth Plant Height
0 46 5 -1 -1 \\ the sum should be 0, not -1
1 48 3 3 2
2 49 3 3 5
3 50 1 1 6
4 51 1 1 7
5 53 0 0 7
6 54 0 0 7
7 55 0 0 7
8 56 0 0 7
9 55 1 1 8
10 51 3 3 11
11 47 4 4 15 \\as a result the final sum is off by 1
只需將h
降至零以下即可將其重置為零
h += newGrowth[i];
if (h < 0) {
h = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.