2016-10-24 6 views
0

私のJavaの宿題は「プラントの成長を追跡するためのJavaプログラムを作成する」ということでした。だから、私の問題は、植物の高さ(H)が負にすることはできませんということですが、私が代わりに-1「H」にJava:負の値を追加しない

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 
+0

を下回った場合、単純にゼロにhをリセット? – BlackHatSamurai

答えて

2

の、私のプログラムは、0またはまったく何も追加作成するかどうかはわかりません`の代わりに-1を加算し、それはあなたが` newGrowth [i]は= 0を行うので、なぜあなたはそれを作ることができないゼロ

h += newGrowth[i]; 

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

うわー...それは簡単です。まあまあありがとう(そうではない)恐ろしいウォンバット、私はこれを忘れることはありません。 – 54mike

関連する問題