How to get the input from user continuously using console application
In this article we are going to see how to get the input from user continuously using console application. We are using while loop to continuously prompt the user for input without exiting out of the console application. Based on user input the execution of the code varies.
In this article we are going to see how to get the input from user continuously using console application. We are using while loop to continuously prompt the user for input without exiting out of the console application. Based on user input the execution of the code varies.
1.Create a class StudentDetails as shown below. It has a method to save the student details to the database.
using System;
namespace ConsoleApplication1
{
public class StudentDetails
{
public string name = "";
public string studentClass="";
public string rollNo;
public string division = "";
public StudentDetails()
{ }
public void Save()
{
//write the code to save the student details to database.
//you can get the student details by using above variables
}
}
}
2.Below code is used to prompt the user for input. if user enters all the details and wants to save the details. user enters "yes" and then the code to save the details to database is executed. If user enters anything other than "yes", then the application continues running and prompts again the user for input.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//This while loop to create infinite loop. to continuosly prompt for student
//details without exiting the program.
while (true)
{
StudentDetails objStudentDetails = new StudentDetails();
GetDetails(objStudentDetails);
}
}
static void GetDetails(StudentDetails objStudentDetails)
{
Console.Write("Name:");
objStudentDetails.name = Console.ReadLine();
Console.Write("Class:");
objStudentDetails.studentClass = Console.ReadLine();
Console.Write("Roll No:");
objStudentDetails.rollNo = Console.ReadLine();
Console.Write("Div:");
objStudentDetails.division = Console.ReadLine();
Console.Write("Do you want to save these data? ");
string userInput = Console.ReadLine();
if (userInput == "yes")
{
//if user input is "yes",save the details to database.
objStudentDetails.Save();
}
else
{ } //Do Nothing
}
}
}