开发者

Java - Program accepting negative numbers when it shouldn't

I have to make a program that uses nested loops to collect data and calculate the average rainfall over a period of years. First, the program should ask for the number of years. (The outer loop will iterate once for each year.) The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.

Input Validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.

I have finished the program, but there is a tiny problem: when it asks for the inches, if I enter 1 for the year it is going to to ask to me input inches 12 times. If I put in a negative number first, it will te开发者_Go百科ll me the number is invalid and then loop again and ask me to put a number equal to or more than zero. Now if I input a series of numbers that are >=0 and then put a negative number, it does not tell me that I cannot put a negative number. It is not supposed to accept negative numbers at all, but it does when the previous 2 or more number were >= zero.

import java.util.Scanner;

public class Averagerainfallteller {
   /**
    * This program tells asks the user to enter an amount of years and then asks
    * the user to given the amount of inches that fell for every month during
    * those years and then give the average rain fall, total inches of rain and
    * total months.
    */
   public static void main(String[] args) {

      double totalInches = 0; 
      double totalMonths = 0; 
      double avgInches = 0; 
      double inches = 0; 
      Scanner kb = new Scanner(System.in);
      System.out.println(" PLease enter the number of years");
      int numYears = kb.nextInt();
      while (!(numYears >= 1)) {
         System.out.println(" PLease enter the number that is more than or equal to one.");
         numYears = kb.nextInt();
      }

      for (int years = 1; years <= numYears; years++) {

         for (int months = 1; months <= 12; months++) {
            System.out.println("How many inches fell for Year: " + years
                  + ", during Month: " + months + "? ");
            inches += kb.nextDouble();
            while (!(inches >= 0)) {
               System.out.println("PLease enter the number that is more than or equal to zero.");
               System.out.println("How many inches fell for Year: " + years
                     + ", during Month: " + months + "? ");
               inches += kb.nextDouble();
            }
         }
      }

      totalMonths = 12 * numYears;
      avgInches = totalInches / totalMonths;
      System.out.println(".....HERE ARE THE RESULTS.....");
      System.out.println("");
      try {
         Thread.currentThread().sleep(1000);
      } catch (Exception e) {
      }
      System.out.println("    Total inches is " + totalInches);
      System.out.println("");
      try {
         Thread.currentThread().sleep(1000);
      } catch (Exception e) {
      }
      System.out.println("    Average Inches is " + avgInches);
      System.out.println("");
      try {
         Thread.currentThread().sleep(1000);
      } catch (Exception e) {
      }
      System.out.println("    Total months is " + totalMonths);
   }
}


Don't do inches +=kb.nextDouble(); instead do input = kb.nextDouble(); if input > 0 then inches += input; otherwise loop. This should help you to filter out negative numbers before your arithmetic logic.


The problem is this:

inches += kb.nextDouble();

Instead try this:

System.out.println("How many inches fell for Year: "+years+", during Month: "+months+ "? ");
inches = kb.nextDouble();    //HERE

while(!(inches>=0))
{


    System.out.println("PLease enter the number that is more than or equal to zero.");
    System.out.println("How many inches fell for Year: "+years+", during Month: "+months+ "? ");
    inches =kb.nextDouble();    //HERE

}

totalInches += inches;    //HERE

Basically you were continuing to add the number input by the user to the same variable inches continuously. Also you seem to use totalInches without initializing it, so it would always be zero.


Make sure a new value for inches (non negative) is entered and than add it up to totalInches.

for (int months = 1; months <= 12; months++) {

    do {
        System.out.println("How many inches fell for Year: " + years + ", during Month: " + months + "? ");
        inches = kb.nextDouble();
    }while(inches < 0);

    totalInches += inches;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜