54mike 54mike - 1 month ago 10
Java Question

Java: Not adding a negative value

Hey guys my Java homework was to: "Write a Java program to track the growth of a plant." So my problem is that the plant's Height(h) cannot be negative, but I'm not sure how to make my program add a 0 or nothing at all, instead of a -1 to "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

Answer

Simply reset h to zero if it goes below zero

h += newGrowth[i];

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