javascript calculate average based on user input array

There is a problem that I am trying to solve, but as a beginner it seems quite challenging. Here is the code I have written so far, however, when I run it only one window appears. Any advice or guidance would be greatly appreciated.

var years = prompt("Enter the number of years: "); // Number of years
var rainFall = new ArrayList();

while (years < 1) {

    alert("Invalid. Enter 1 or greater: ");
    years = prompt("Enter a year: ");
}

for (var y = 1; y <= years; y++) {

    for (var m = 1; m <= NUM_MONTHS; m++) {

        alert("Year " + y + ", month " + m + ": ");
        monthRain = prompt("Enter rainfall for a month ");
        rainfall.add(monthRain);
    }
}

alert("\nNumber of months: " + (years * NUM_MONTHS) + "Total rainfall: " + calculateTotalRainfall(rainfall) + " inches" + "Average monthly rainfall: " + calculateAverageRainfall(rainfall) + " inches");

Answer №1

    Array.prototype.sum = function() {
      var total = 0;
      for(var i in this) {
        var i = parseFloat(this[i]);
        if(i>=0) {
          total += i;
        }
      }
      return total;
    };

    Array.prototype.avg = function() {
      var avg = (this.length>0)? parseFloat(this.sum()/this.length) : 0;
      avg = parseFloat(parseInt(avg*100)/100);
      return avg;
    };

    var years = parseInt(prompt("Enter the number of years: ")); // Number of years

    var rainFall = [];

    while (years < 1) {
      alert("Invalid. Enter 1 or greater: ");
      years = parseInt(prompt("Enter a year: "));
    }

    var NUM_MONTHS = 12;
    for (var y = 1; y <= years; y++) {
      for (var m = 1; m <= NUM_MONTHS; m++) {
        alert("Year " + y + " month " + m + ": ");

        var monthRain = parseFloat(prompt("enter rainfall for a month "));
        if(monthRain>=0) {
          rainFall.push(monthRain);
        }
      }
    }

 if(years<1) years = 0;
 alert("\nNumber of months: " + (years * NUM_MONTHS) + "   Total rainfall: " + rainFall.sum() + " inches" + "   Average monthly rainfall: " + rainFall.avg() + " inches");

OR:

    function sumArray (items) {
      var total = 0;
      for(var i in items) {
        var i = parseFloat(items[i]);
        if(i>=0) {
          total += i;
        }
      }
      return total;
    };

    function avgArray(items) {
      var sum = sumArray(items);
      var avg = (items.length>0)? parseFloat(sum/items.length) : 0;
      avg = parseFloat(parseInt(avg*100)/100);
      return avg;
    };

    var years = parseInt(prompt("Enter the number of years: ")); // Number of years

    var rainFall = [];

    while (years < 1) {
      alert("Invalid. Enter 1 or greater: ");
      years = parseInt(prompt("Enter a year: "));
    }

    var NUM_MONTHS = 12;
    for (var y = 1; y <= years; y++) {
      for (var m = 1; m <= NUM_MONTHS; m++) {
        alert("Year " + y + " month " + m + ": ");

        var monthRain = parseFloat(prompt("enter rainfall for a month "));
        if(monthRain>=0) {
          rainFall.push(monthRain);
        }
      }
    }

 if(years<1) years = 0;
 alert("\nNumber of months: " + (years * NUM_MONTHS) + "   Total rainfall: " + sumArray(rainFall) + " inches" + "   Average monthly rainfall: " + avgArray(rainFall) + " inches");

Answer №2

Consider replacing rainfall.add(monthRain); with rainfall.push(monthRain);

Answer №3

It appears that the main issue was the utilization of the Java ArrayList class instead of the JavaScript Array class. Remember, Java and JavaScript are two distinct languages despite their confusingly similar names.

To resolve this, simply switch from using new ArrayList() to new Array(), and change rainfall.add to rainFall.push (be mindful of the change in capitalization as well).

If you have a JavaScript console inspector available (such as the one found in Chrome by pressing ctrl-shift-J), you can identify any JS errors occurring in your code, such as when ArrayList could not be located.

I've made the necessary corrections below and included the absent NUM_MONTHS constant (which I presume was defined elsewhere).

var NUM_MONTHS = 12;
var years= prompt("Enter the number of years: "); // Number of years

// CORRECTION: use "Array" instead of "ArrayList". Alternatively, you can also use "var rainFall = [];", which is another approach I prefer
var rainFall = new Array();

while (years < 1) {
    alert("Invalid. Enter 1 or greater: ");
    years =prompt("Enter a year: ");
}

for (var y = 1; y <= years; y++) {
    for (var m = 1; m <= NUM_MONTHS; m++) {
        alert("Year " + y + " month " + m + ": ");
        monthRain = prompt("enter rainfall for a month ");
        
        // CORRECTION: utilize the "push()" method of Array and maintain camelCase consistency for variable names
        rainFall.push(monthRain);
    }
}

alert("\nNumber of months: " + (years * NUM_MONTHS) + "Total rainfall: " + calculateTotalRainFall(rainFall) + " inches" + "Average monthly rainfall: " + calculateAverageRainFall(rainFall) + " inches");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

Allow AngularJS to make HTTP POST requests with CORS enabled

I am looking to submit a form to send an HTTP POST request to a server located on a different domain, with CORS enabled in the server script using Node.js. Below is the Angular configuration script: var myApp = angular.module('myApp', ['ng ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Performing a double iteration on a JSON array using nested foreach loops to associate each index with its

I have successfully decoded a JSON array +"productINF": {#1260 ▼ +"product": {#1011 ▼ +"productCode": "123" +"productType": {#999 ▼ +"count": 3.0 +"desc": "Block" } } } +"price": {#1267 ▼ +"02": "470.00" } Now, I am ...

Guide on converting JSON into PHP array

Struggling to convert a JSON output into a PHP array due to nested arrays within the data. This is my first time delving into PHP and JSON, and I am facing some obstacles with the json_decode() function. Any assistance would be highly appreciated. Below i ...

I rely on the handleChange function to update the state value, but unfortunately, it remains unchanged

In my project, I am working on creating multiple responsive forms (form1, form2, and form3) within the same page using framer motion. However, I am facing an issue where the state value is not updating correctly when users fill out the form. Specifically, ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

The Angular frontend appears to be experiencing difficulties displaying content on the website

I'm currently working through the AngularJS on Rails tutorial from Thinkster(). Check out my progress so far https://jsfiddle.net/dcbavw4e/ I'm not seeing anything on the web page. I've already installed node.js and npm. Are there any othe ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Resetting the countdown timer is triggered when moving to a new page

In my current project, I am developing a basic battle game in which two players choose their characters and engage in combat. The battles are structured into turns, with each new turn initiating on a fresh page and featuring a timer that counts down from ...

Creating a universal function to handle setTimeout and setInterval globally, inclusive of clearTimeout and clearInterval for all functions

Is it possible to create a universal setTimeout and setInterval function with corresponding clearTimeout and clearInterval for all functions while passing values to them? The situation is as follows: 1. More than 8 functions utilizing setInterval for act ...

Obtain access to global.window.localStorage within getServerSideProps

I have a component that receives props with data and renders the data. In my functionality within the getServerSideProps, I am attempting to retrieve data from localStorage. However, due to window being undefined, I am unable to do so. I have tried using ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

MySQL Entry Update Failure

This is the HTML/EJS code snippet: <div class="Edit-Panel" style="display: none;"> <div class="Edit-Wrapper"> <div class="Editing"> <p class="Edit-Header ...

Leveraging the power of JavaScript and jQuery to identify comparable SELECT choices

My current approach involves utilizing the .filter() method to match the value of an INPUT field (prjName) with an option in a SELECT field (prjList). However, this method only works when there is an exact match for the option text: $("select[title=' ...

In JavaScript, unchecking a radio button results in all options becoming uncheckable

I have a pure CSS accordion and I want to enhance it with some JavaScript functionality for users who have JavaScript enabled. The CSS accordion currently utilizes the :checked pseudo-class. The new feature I am looking to add is: if a button that is alre ...

Braintree drop-in feature now allows for automatic disabling of the submit button while the transaction

I've been struggling with a seemingly simple task that I just can't seem to figure out. I'm using Braintree's dropin UI and I have a submit button that I need to disable while the processing is happening, but I can't seem to find t ...

The argument provided must be a string comprising of either 12 bytes, a string containing 24 hex characters, or an integer in order to avoid a BSONTypeError

After building a CRUD application using the MERN stack, I attempted to implement a search operation but encountered an error: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer Below is the code ...