繁体   English   中英

Java:不添加负值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM