A way to condense multiple readlines?

2019-07-22 00:13发布

问题:

Im pretty new to programming so i dont know much myself other than what we've done in my into c# class so far but i've looked pretty much everywhere for a way to condense readlines so that the program will read many inputs in a row without having to code a readline for every variable the user is inputting for.

        Console.WriteLine("Enter ID for Jane Doe: ");
        c.ID = Console.ReadLine();

        Console.WriteLine("Enter Insurance Name for Jane Doe: ");
        c.Insurance = Console.ReadLine();

        Console.WriteLine("Enter Height(In.) for Jane Doe: ");
        c.Height = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter Weight(lbs.) for Jane Doe: ");
        c.Weight = Convert.ToSingle(Console.ReadLine());

        Console.WriteLine("Enter Health Status for Jane Doe: ");
        c.HealthStatus = Console.ReadLine();

This example is from some homework from a little bit ago but it bothered me that I couldn't find a way to condense the code. Basically I want to be able to ask for all the information in one writeline and then only use one readline/other method for the input of each variable where the user types the info for one variable, hits enter, then repeats however often is needed. Is there any way to do that or do i just have to deal with the repetition?

回答1:

In general, you need to just deal with the repetition. Its clear, easy to debug, and its really not that bad.

Now, you could do this:

public class InputRequest
{
     public String Request {get; set;}
     public Action InputMethod {get; set;}
}

Which you would then create like so:

List<InputRequest> allInputs = new List<InputRequest>();
allInputs.Add(new InputRequest() { Request = "Enter your height", 
    InputMethod = new Action(() => currentPerson.Height = Convert.ToInt32(Console.ReadLine())));

Then you could iterate through them:

foreach (InputRequest req in allInputs)
{
    Console.WriteLine(req.Request);
    req.InputMethod();
}

But in all reality, that removes a lot of readability for the sake of slightly smaller code. I would use such a pattern in a different context perhaps, but here, your code is fine.



回答2:

Honestly, to the best of my knowledge there isn't much better. You could try this for readability/reusability

public String promtUser(String prompt)
{
    Console.WriteLine(prompt + ": ");
    return Console.ReadLine()
}

Simple and reusable. Not perfect though.



回答3:

If I was asking many questions and they were for a handful of data type responses I'd probably go with the following:

    var answer1 = AskString("Give me a string:");
    var answer2 = AskInt   ("Give me an int:");
    var answer3 = AskSingle("Give me a single:");

with supporting methods like below

    Single AskSingle(string text)
    {
        Console.WriteLine(text);
        return Convert.ToSingle(Console.ReadLine());
    }

Simple and readable. I wouldn't bother unless there were several questions being asked though. Also can include in the "Ask" methods validation code for the data type you expect. For example if you expect an int and get a string you could give the user a chance to re-type it, or throw an error back to them.



回答4:

Thats it I'm afraid! The best way anyway, you can always read one string then split it but that would involve extra handling and more time consuming.. that way would be

Console.WriteLine("Please enter info in the following format");
Console.WriteLine("ID Name Height Weight Status");

data = Console.ReadLine();
var info = data.Split(" ");
c.Id = info[0];
c.Insurance = info[1];
c.Height = int.Parse(info[2]);

etc...

The way you have it you could do extra handling such as

int value;
do
{
    Console.WriteLine("Enter Height");
}
while(int.TryParse(Console.ReadLine(), out value))

This would keep your users in a loop until they enter a valid height



回答5:

For occasional use where readability is preferred over compactness, you might try something like this to do a simple multi-field parse of a single line of input.

Console.Write("Enter the following info for Jane Doe, separated by commas:\n" +
              "    ID, Insurance Name, Height(in.), Weight(lbs.), Health Status.\n" +
              "==> ");
string input = Console.ReadLine();

char[] separators = {','};
string[] values = input.Split(separators);
c.ID           = (values.Count() >= 1) ? values[0].Trim() : null;
c.Insurance    = (values.Count() >= 2) ? values[1].Trim() : null;
c.Height       = (values.Count() >= 3) ? values[2].Trim() : null;
c.Weight       = (values.Count() >= 4) ? values[3].Trim() : null;
c.HealthStatus = (values.Count() >= 5) ? values[4].Trim() : null;


标签: c# readline