So I'm trying to make a program that allows users to insert values for length and width and then another method is called to calculate the area and perimeter. Howevever, I can't seem to get past the user input part.
The whole program is closed after I hit enter for the length. I read that the Read command is terminated after you hit the enter key, so all I'm wondering is how am I supposed to go about enabling a user to enter multiple values. I tried putting WriteLine commands in between the Read commands, but that doesn't stop the program from closing.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntroToCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Length?");
int length = Console.Read();
Console.WriteLine("Width?");
int width = Console.Read();
Console.WriteLine("Good!");
Perimeter(length, width);
}
public static double Area(int length, int width)
{
return length * width;
}
}
}
Console.Read
only reads a single character - but it will wait until you've hit enter in order to do so. So what's happening is that you're typing something then hitting enter, then Console.Read
will return, then you'll try to read another character - which is already there!
To read an integer as a complete line, you should use something like:
string line = Console.ReadLine();
int width = int.Parse(line);
Note that this will throw an exception if the value can't be parsed. Consider using int.TryParse
instead, to handle invalid user input cleanly.
Once you've reached the end of the program, it may terminate automatically or it may wait for you to hit return - depending on how you're running it. You can always add another call to Console.ReadLine()
to force it to wait for the user to hit enter at least one more time (or two in some cases). Or run the program from the command line, in which case it will terminate but you'll still see the results.
See more on this question at Stackoverflow