C# program control

  • Christian Chat is a moderated online Christian community allowing Christians around the world to fellowship with each other in real time chat via webcam, voice, and text, with the Christian Chat app. You can also start or participate in a Bible-based discussion here in the Christian Chat Forums, where members can also share with each other their own videos, pictures, or favorite Christian music.

    If you are a Christian and need encouragement and fellowship, we're here for you! If you are not a Christian but interested in knowing more about Jesus our Lord, you're also welcome! Want to know what the Bible says, and how you can apply it to your life? Join us!

    To make new Christian friends now around the world, click here to join Christian Chat.
W

wwjd_kilden

Guest
#1
So, this is probably a noob question, but my experience with programming is limited, and I haven't used it for some time.

I try to play around with code to get used to program control and scope, and realize I am not very good at it :p

My current problem is with looping a program in the correct way (or maybe I need to do something entirely different?)
Let's say I want to prompt the user for input twice, asking for a number, and then multiply the numbers.
I want to make it so that the program keeps asking for each number until it is correctly given. How do I go about this, seeing as my code does not know I make sure the value is assigned to the variable?

so, I want my program to work like this

Enter nr 1
< if failed > Enter nr 1
<if ok >
Enter nr 2
<if entering nr 2 not ok > Enter nr 2

I get it to work loop, but a wrong value at query nr 2 causes the program to re- loop at query one .
(Which makes sense with all my code being embedded by the same loop, I just don't know how to write the code to avoid it). In what way do I enclose my code in a loop to make it work? If I use two loops, my program has the problem of not knowing whether both variables are assigned.

bool run = true;
int firstnr;
int secondnr;

Console.WriteLine(" Multiplication \n");

while (run) {

Console.Write("Enter first number: ");

if (!Int32.TryParse(Console.ReadLine(), out firstnr)) {

Console.WriteLine("Input not recognized as a number");
continue;
}

Console.Write("Enter second number: ");
if (!Int32.TryParse(Console.ReadLine(), out secondnr))
{

Console.WriteLine("Input not recognized as a number");
// Possible to retrace only this step, rather than entire loop?
}
else {

Console.WriteLine("Sum: " + (firstnr * secondnr));
break;
}
}
Console.ReadLine();
}

-----------
Enter first number: a
Input not recognized as a number
Enter first number: 2
Enter second number: a
Input not recognized as a number
Enter first number:
..............
So, if possible, I want to make it keep asking for the number that it it waiting for in the flow, rather than going back to the beginning.