CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Feb 2013
    Posts
    23

    Load user input into 10x4 rectangular array

    Ok, I am working on a form that calculates the future value of an investment. I need to add a 10x4 rectangular array (required) and then display the results when the user clicks exit. I am having trouble figuring out how to load the user input into the array. Here's what I have so far:

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FutureValue
    {
        // This is the starting point for exercise 8-2 from
        // "Murach's C# 2010" by Joel Murach
        // (c) 2010 by Mike Murach & Associates, Inc. 
        // www.murach.com
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
            }
    
            // TODO: Declare the rectangular array and the row index here
            int[,] calculations = new int[10, 4];
            int numberOfRows = calculations.GetLength(0);
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsValidData())
                    {
                        decimal monthlyInvestment =
                            Convert.ToDecimal(txtMonthlyInvestment.Text);
                        decimal interestRateYearly =
                            Convert.ToDecimal(txtInterestRate.Text);
                        int years = Convert.ToInt32(txtYears.Text);
    
                        int months = years * 12;
                        decimal interestRateMonthly = interestRateYearly / 12 / 100;
    
                        decimal futureValue = CalculateFutureValue(
                            monthlyInvestment, interestRateMonthly, months);
                        txtFutureValue.Text = futureValue.ToString("c");
                        txtMonthlyInvestment.Focus();
    
                        // TODO: Add the calculation to the rectangular array here
                        
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n\n" +
                        ex.GetType().ToString() + "\n" +
                        ex.StackTrace, "Exception");
                }
            }
    
            public bool IsValidData()
            {
                return
                    // Validate the Monthly Investment text box
                    IsPresent(txtMonthlyInvestment, "Monthly Investment") &&
                    IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&
                    IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) &&
    
                    // Validate the Yearly Interest Rate text box
                    IsPresent(txtInterestRate, "Yearly Interest Rate") &&
                    IsDecimal(txtInterestRate, "Yearly Interest Rate") &&
                    IsWithinRange(txtInterestRate, "Yearly Interest Rate", 1, 20) &&
    
                    // Validate the Number of Years text box
                    IsPresent(txtYears, "Number of Years") &&
                    IsInt32(txtYears, "Number of Years") &&
                    IsWithinRange(txtYears, "Number of Years", 1, 40);
            }
    
            public bool IsPresent(TextBox textBox, string name)
            {
                if (textBox.Text == "")
                {
                    MessageBox.Show(name + " is a required field.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            public bool IsDecimal(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToDecimal(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be a decimal value.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsInt32(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToInt32(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be an integer.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsWithinRange(TextBox textBox, string name,
                decimal min, decimal max)
            {
                decimal number = Convert.ToDecimal(textBox.Text);
                if (number < min || number > max)
                {
                    MessageBox.Show(name + " must be between " + min
                        + " and " + max + ".", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            private decimal CalculateFutureValue(decimal monthlyInvestment,
               decimal monthlyInterestRate, int months)
            {
                decimal futureValue = 0m;
                for (int i = 0; i < months; i++)
                {
                    futureValue = (futureValue + monthlyInvestment)
                        * (1 + monthlyInterestRate);
                }
    
                return futureValue;
            }
    
            private void btnExit_Click(object sender, EventArgs e)
            {
                // TODO: Display the rectangular array in a dialog box here
                string calculationsString = "";
                        for (int i = 0; i < calculations.GetLength(0); i++)
                        {
                            for (int j = 0; j < calculations.GetLength(1); j++
                                calculationsString += calculations[i,j] + " ";
    
                            calculationsString += "\n";
                        }
                MessageBox.Show(calculationsString, "Future Value Calculations");
    
                this.Close();
            }
    
        }
    }
    int numberOfRows = calculations.GetLength(0); is also giving me an error "A field initializer cannot reference the non-static field, method, or property 'FutureValue.form1.calculations'
    Do I need to assign values to the array first?

    I already coded the message box at the end, I just mainly need to know how to enter the user input into the array. Thanks for your help.

  2. #2
    Join Date
    Feb 2013
    Posts
    23

    Re: Load user input into 10x4 rectangular array

    This is how I loaded input from a form with a basic 5 element array, how would I modify this to enter into a 10x4 array?

    Code:
    for (int i = totals.Length - 1; i > 0; i--)
                            { 
                                totals[i] = totals[i - 1];
                            }

  3. #3
    Join Date
    Jun 2011
    Location
    .NET4.0 / VS 2010
    Posts
    70

    Re: Load user input into 10x4 rectangular array

    In a class right now so have to make a brief response but to populate a multidimensional array you could create a nested loop.

    Example:
    Code:
            static void Main(string[] args)
            {
                Random rnd = new Random();
                int[,] numList = new int[3, 2];
    
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        numList[i, j] = rnd.Next(1,11);
                    }
                }
    
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        Console.WriteLine(numList[i, j]);
                    }
                }
    
                // Pause application.
                Console.Write("Press any key to continue...");
                Console.ReadKey();
            }
    I am not completely sure if that answered your question but if not I am sure one of the more knowledgeable members will come in and help you shortly. If not when I get a chance later I will try to help out with more detail.

  4. #4
    Join Date
    Feb 2013
    Posts
    23

    Re: Load user input into 10x4 rectangular array

    Still not really getting this, I just need someone to explain how it's supposed to work and help me integrate it into my code above.

  5. #5
    Join Date
    Jun 2011
    Location
    .NET4.0 / VS 2010
    Posts
    70

    Re: Load user input into 10x4 rectangular array

    2 Dimensional arrays are not much more complicated than single element arrays. You populate them in a similar manner. In your code I do not see any attempt at populating the array though. I see in on exit you make an attempt to display it through a nested loop but there is no information saved into the array to be displayed.

    2 Dimensional array
    Code:
    [2,2]
    [0,0] [0,1]
    [1,0] [1,1]
    So you know you need to populate the array. If you are reading data from a file it is simple since you know the array will be fully populated and can use a nested loop to store the information into the array. Now from the looks of it if I understand your code correctly you are attempting to store the value calculated into the array each time something is calculated. Then at the end when you exit you want to display all the calculations.

    Well to store the data you will need to create some counters and some checks to make sure you are not out of bounds of the array. Something such as the following would work.

    Pseudo code:
    Code:
    int currentRow = 0;
    int currentColumn = 0;
    
    Check for valid data.
    calculations[currentRow, currentColumn] = valid data
    
    Check that columns are within range if not check that rows are still within range and change counter values.
    if (currentColumn < calculations column maximum)
       currentColumn++;
    else if (currentRow < calculations row maximum)
    {
       currentRow++;
       currentColumn = 0;
    }
    Simply put what the code will do is once the data is validated it will store the information into the array. Once saved it will check that the current column is still within the array bounds. If it is then it will add to the counter so it can save into the next position in the array. If it is higher than the maximum column then it checks if the rows are still within range. If it is same thing it will add to the row counter to move to the next row and reset the column counter. It will keep doing this until the array is filled in which case it will only replace the last position of the array.

    Try integrating code that populates your array and post what errors you get.

  6. #6
    Join Date
    Feb 2013
    Posts
    23

    Re: Load user input into 10x4 rectangular array

    I get an error that < cannot be applied to operands of type int

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FutureValue
    {
        // This is the starting point for exercise 8-2 from
        // "Murach's C# 2010" by Joel Murach
        // (c) 2010 by Mike Murach & Associates, Inc. 
        // www.murach.com
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                
            }
    
            // TODO: Declare the rectangular array and the row index here
            int[,] calculations = new int[10, 4];
            int numberOfRows = calculations.GetLength(0);
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsValidData())
                    {
                        decimal monthlyInvestment =
                            Convert.ToDecimal(txtMonthlyInvestment.Text);
                        decimal interestRateYearly =
                            Convert.ToDecimal(txtInterestRate.Text);
                        int years = Convert.ToInt32(txtYears.Text);
    
                        int months = years * 12;
                        decimal interestRateMonthly = interestRateYearly / 12 / 100;
    
                        decimal futureValue = CalculateFutureValue(
                            monthlyInvestment, interestRateMonthly, months);
                        txtFutureValue.Text = futureValue.ToString("c");
                        txtMonthlyInvestment.Focus();
    
                        // TODO: Add the calculation to the rectangular array here
                        int currentRow = 0;
                        int currentColumn = 0;
    
                        //Check for valid data.
                        //calculations[currentRow, currentColumn] = valid data
    
                        //Check that columns are within range if not check that rows are still within range and change counter values.
                        if (currentColumn < calculations column maximum)
                            currentColumn++;
                        else if (currentRow < calculations row maximum)
                        {
                            currentRow++;
                            currentColumn = 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n\n" +
                        ex.GetType().ToString() + "\n" +
                        ex.StackTrace, "Exception");
                }
            }
    
            public bool IsValidData()
            {
                return
                    // Validate the Monthly Investment text box
                    IsPresent(txtMonthlyInvestment, "Monthly Investment") &&
                    IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&
                    IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) &&
    
                    // Validate the Yearly Interest Rate text box
                    IsPresent(txtInterestRate, "Yearly Interest Rate") &&
                    IsDecimal(txtInterestRate, "Yearly Interest Rate") &&
                    IsWithinRange(txtInterestRate, "Yearly Interest Rate", 1, 20) &&
    
                    // Validate the Number of Years text box
                    IsPresent(txtYears, "Number of Years") &&
                    IsInt32(txtYears, "Number of Years") &&
                    IsWithinRange(txtYears, "Number of Years", 1, 40);
            }
    
            public bool IsPresent(TextBox textBox, string name)
            {
                if (textBox.Text == "")
                {
                    MessageBox.Show(name + " is a required field.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            public bool IsDecimal(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToDecimal(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be a decimal value.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsInt32(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToInt32(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be an integer.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsWithinRange(TextBox textBox, string name,
                decimal min, decimal max)
            {
                decimal number = Convert.ToDecimal(textBox.Text);
                if (number < min || number > max)
                {
                    MessageBox.Show(name + " must be between " + min
                        + " and " + max + ".", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            private decimal CalculateFutureValue(decimal monthlyInvestment,
               decimal monthlyInterestRate, int months)
            {
                decimal futureValue = 0m;
                for (int i = 0; i < months; i++)
                {
                    futureValue = (futureValue + monthlyInvestment)
                        * (1 + monthlyInterestRate);
                }
    
                return futureValue;
            }
    
            private void btnExit_Click(object sender, EventArgs e)
            {
                // TODO: Display the rectangular array in a dialog box here
                string calculationsString = "";
                        for (int i = 0; i < calculations.GetLength(0); i++)
                        {
                            for (int j = 0; j < calculations.GetLength(1); j++)
                                calculationsString += calculations[i,j] + " ";
    
                            calculationsString += "\n";
                        }
                MessageBox.Show(calculationsString, "Future Value Calculations");
    
                this.Close();
            }
    
        }
    }

  7. #7
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Load user input into 10x4 rectangular array

    Quote Originally Posted by Inigo Montoya View Post
    I get an error that < cannot be applied to operands of type int
    It would help to know which line the error occurred on (and I don't mean for you to answer with "line 46" .. i mean "if(currentColumn < calculations column maximum)" )

    That said, on that line there I pasted..

    if(currentColumn < calculations column maximum)


    You cannot put spaces in a variable name, so tell me, what do you mean with this line of code? what is it supposed to do?

    The biggest problem with your program as it stands is that you're going straight to coding without thinking about it first. You should write your algorithm and logic in plain english (or your chosen first language) first and then code after. Here's an example, for iterating over a 2D array:

    Code:
    //first we declare a 2d array
    //then we need a for loop which will iterate over one dimension
      //inside this for loop, another for loop iterates over the other dimension
       //print out what we find at this array location
    That's the logic, NOW write the code, and leave the comments in there


    Code:
    //first we declare a 2d array
    string[,] sA = new string[10,4];
    
    //then we need a for loop which will iterate over one dimension (in this case the rows or vertical)
    for(int r= 0; r < sA.Length; r++){
    
      //inside this for loop, another for loop iterates over the other dimension
      for(int c = 0; c < sA[r].Length; c++){
    
       //put a value into it array location
       sA[r,c] = "A value at row " + r + ", column " + c;
    
      }
    }
    Right now, without guidance (comments) you're just coding by hope, it's frustrating and unrewarding. Write first what you mean to do, check that it's correct, then code what you wrote, then test it. If it doesnt work out first ask "where is the problem?" then ask "does the code do what I commented that it should?" then ask "is the logic of the comment correct?"

    Somewhere along the way you'll find the mistake

    -
    Tip: a 2D array is just an array of arrays. You understand that an array is a list of values, like pages in a book.. page[1], page[227] ?
    Well now that your book, and look at the library.. the library is a list of books, an array of arrays. I could say library[13,227] and it would mean "go to the 13th book, and get the 227th page"
    Wanna make it 3 dimensions? Lets get all the libraries in the country.. allofthem[72,13,227] .. go to the 72nd library, get the 13th book, get page 227
    Wanna make it 4 dimensions? Let's get all the countries of the world, and all their libraries, and all their books, and all their pages..

    And so on

    Actually, we find in programming that 2D arrays declared like array[,] arent as useful because every book has the same number of pages, every library has the same number of books.. You'll move on to using arrays like int[][] books = new int[10][]; -- this means "I know I have 10 books in my library, but I don't know right now how many pages each book has"
    For that you need to do more code:
    books[0] = new int[235]; //the first book as 235 pages
    books[1] = new int[421]; //the second book has 421 pages

    All youre doing with int[][] books = new int[10][]; is saying "I want an array that is 10 long, and it will hold in each slot, another array of unknown length"

    But I digress.. back to your problem.. take the code you wrote and save it, then trash it and start a new project. WRITE COMMENTS FIRST. Even pro programmers do this after being on the job 15 years. It helps them think, and helps people who come along after see what they were thinking.
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  8. #8
    Join Date
    Feb 2013
    Posts
    23

    Re: Load user input into 10x4 rectangular array

    Ok, so I have it mostly figured out now, thanks to everyone's help. I declared the array and am using the variable "r" to designate the rows. You can see in the code where I am loading each field into the array using "r" as the row. Stuck on how to increment r after each instance of the calculations, should be easy for me by now but just not getting it.

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FutureValue
    {
        // This is the starting point for exercise 8-2 from
        // "Murach's C# 2010" by Joel Murach
        // (c) 2010 by Mike Murach & Associates, Inc. 
        // www.murach.com
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                
            }
    
            // TODO: Declare the rectangular array and the row index here
            string[,] futureValueArray = new string[10, 4];
            int r = 0;
            
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsValidData())
                    {
                        decimal monthlyInvestment =
                            Convert.ToDecimal(txtMonthlyInvestment.Text);
                        decimal interestRateYearly =
                            Convert.ToDecimal(txtInterestRate.Text);
                        int years = Convert.ToInt32(txtYears.Text);
    
                        int months = years * 12;
                        decimal interestRateMonthly = interestRateYearly / 12 / 100;
    
                        decimal futureValue = CalculateFutureValue(
                            monthlyInvestment, interestRateMonthly, months);
                        txtFutureValue.Text = futureValue.ToString("c");
                        txtMonthlyInvestment.Focus();
    
                        // TODO: Add the calculation to the rectangular array here
                        futureValueArray[r, 0] = monthlyInvestment.ToString("c2");
                        futureValueArray[r, 1] = interestRateYearly.ToString();
                        futureValueArray[r, 2] = years.ToString();
                        futureValueArray[r, 3] = futureValue.ToString("c2");
                        int r = r++;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n\n" +
                        ex.GetType().ToString() + "\n" +
                        ex.StackTrace, "Exception");
                }
            }
    
            public bool IsValidData()
            {
                return
                    // Validate the Monthly Investment text box
                    IsPresent(txtMonthlyInvestment, "Monthly Investment") &&
                    IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&
                    IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) &&
    
                    // Validate the Yearly Interest Rate text box
                    IsPresent(txtInterestRate, "Yearly Interest Rate") &&
                    IsDecimal(txtInterestRate, "Yearly Interest Rate") &&
                    IsWithinRange(txtInterestRate, "Yearly Interest Rate", 1, 20) &&
    
                    // Validate the Number of Years text box
                    IsPresent(txtYears, "Number of Years") &&
                    IsInt32(txtYears, "Number of Years") &&
                    IsWithinRange(txtYears, "Number of Years", 1, 40);
            }
    
            public bool IsPresent(TextBox textBox, string name)
            {
                if (textBox.Text == "")
                {
                    MessageBox.Show(name + " is a required field.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            public bool IsDecimal(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToDecimal(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be a decimal value.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsInt32(TextBox textBox, string name)
            {
                try
                {
                    Convert.ToInt32(textBox.Text);
                    return true;
                }
                catch (FormatException)
                {
                    MessageBox.Show(name + " must be an integer.", "Entry Error");
                    textBox.Focus();
                    return false;
                }
            }
    
            public bool IsWithinRange(TextBox textBox, string name,
                decimal min, decimal max)
            {
                decimal number = Convert.ToDecimal(textBox.Text);
                if (number < min || number > max)
                {
                    MessageBox.Show(name + " must be between " + min
                        + " and " + max + ".", "Entry Error");
                    textBox.Focus();
                    return false;
                }
                return true;
            }
    
            private decimal CalculateFutureValue(decimal monthlyInvestment,
               decimal monthlyInterestRate, int months)
            {
                decimal futureValue = 0m;
                for (int i = 0; i < months; i++)
                {
                    futureValue = (futureValue + monthlyInvestment)
                        * (1 + monthlyInterestRate);
                }
    
                return futureValue;
            }
    
            private void btnExit_Click(object sender, EventArgs e)
            {
                // TODO: Display the rectangular array in a dialog box here
                string calculationsString = "";
                        for (int i = 0; i < futureValueArray.GetLength(0); i++)
                        {
                            for (int j = 0; j < futureValueArray.GetLength(1); j++)
                                calculationsString += futureValueArray[i,j] + " ";
    
                            calculationsString += "\n";
                        }
                MessageBox.Show(calculationsString, "Future Value Calculations");
    
                this.Close();
            }
    
        }
    }

  9. #9
    Join Date
    Jun 2011
    Location
    .NET4.0 / VS 2010
    Posts
    70

    Re: Load user input into 10x4 rectangular array

    In your Calculate method there is not need to create and initialize the variable again. You simply have to do r++ which is the equivalent to doing r = r + 1 or r += 1 they all do the same thing. Also like mentioned in my previous post you will want to make sure that r does not go past the array's size in this case it is 10. What happens when the user enters 10 different calculations and they decide to enter an 11th one?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured