tags:

views:

148

answers:

2

Hi,

I'm in my first OOP class, and I was wondering if there was any way to use a loop (for, while, do-while) do loop through the process below twice, but store the results of the second iteration through the loop in two new variables, and then create a second ComplexNumber object using those variable values from the second iteration?

        Console.Write("Real part: ");
        double realValue = double.Parse(Console.ReadLine());

        Console.Write("Complex part: ");
        double complexValue = double.Parse(Console.ReadLine());

        ComplexNumber firstComplex = new ComplexNumber(realValue, complexValue);
A: 

Well, sort of.

You can use an array of doubles to gather the input, but then when you get to passing them in as parameters to the constructor, you'll need to access the indexes directly, to get them out. Try and write the code yourself and ask again if you're stuck.

Noon Silk
k, I'll see what I can do.
Alex
ah, I got it, thanks for not posting code and instead pointing me in the right direction
Alex
No worries mate :)
Noon Silk
+4  A: 

Local scoping within the for loop keeps us from needing unique variables each time.

ComplexNumber[] complexNumbers = new ComplexNumber[2];

for (int i = 0; i < complexNumbers.Length; i++)
{
        Console.Write("Real part: ");
        double realValue = double.Parse(Console.ReadLine());

        Console.Write("Complex part: ");
        double complexValue = double.Parse(Console.ReadLine());
        complexNumbers[i] = new ComplexNumber(realValue, complexValue);
}
FlySwat
Thanks, but I was trying to figure this out for myself, and just wanted some pointers in the right direction.
Alex
Well, sorry for helping then.
FlySwat
Thanks, I ended up doing this, but you can be sure I didn't just copy/paste, I learned for myself.
Alex
no no, I really appreciate it, I apologize if I came off rude.
Alex
I upvoted it. :)
Alex
+1 Nice and quick!
KMan