Java:不添加负值

时间:2016-10-24 23:51:30

标签: java

嘿伙计们,我的Java作业是:“编写一个Java程序来跟踪工厂的增长。”所以我的问题是植物的高度(h)不能为负,但我不知道如何让我的程序添加0或者根本不添加,而不是-1到“h”

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

1 个答案:

答案 0 :(得分:2)

如果低于零,只需将h重置为零

h += newGrowth[i];

if (h < 0) {
   h = 0;
}