C# Console Application - Calling Main method or Class? - c#

I have exercise/drill/homework assignment to create a C# program to compute the value of a number raised to the power of a second number. Read the two numbers from the keyboard.
Ask the user for an integer.
Print the integer back to the screen and asked if it is correct.
If the integer is correct, continue on.
If the integer is incorrect, start program from the beginning.
I have two questions:
Can and how do I programmatically clear the console window?
Start over, do I call the Main method or the Class?
How do I do either, calling the main method or the class?
Here's what I've written so far:
using System;
using System.Text;
namespace CalcPowerOfNums
{
class Program
{
//Declaring the two main string variables to be used in our calculation.
string firstUserString;
string secondUserString;
static void Main(string[] args)
{
//Ask the user for the first number.
Console.WriteLine("Enter your first number and press the Enter/Return key");
string firstUserString = Console.ReadLine();
//Make sure this number is correct.
Console.WriteLine("You want to find the power of {0}?\n" , firstUserString);
//Declaring, Initializing string variables for user answer.
string firstAnswer = "";
//Make user confirm or deny their choice.
Console.WriteLine("Press the lowercase letter y for yes");
Console.WriteLine("Press the lowercase letter n for no");
Console.ReadKey();
//If user answer is yes, move on… It user answer is no, start program over.
do
{
if (firstAnswer == "y")
continue;
if (firstAnswer == "n")
}

Looking at the Console class, you will find a Clear method that will clear the console screen. As to calling Main, that will be called automatically by default in a console project as long as you have declared it. You can have a look in your project properties at the Startup Object setting.

When you say "start the program over" I am assuming you mean clear the window and ask for the input again, not reload the entire process.
You can use Console.Clear() to clear the console window. The main method is called automatically from Program.cs. Just place your main code in a while loop and loop until you get the desired input. If you don't get the desired input, just issue a Console.Clear() and ask again until you do.

I have two questions: Can and how do I programmatically clear the console window?
Yes, by calling Console.Clear.
Do I call the Main method or the Class?
You cannot invoke a class, and you should never call main directly. Just put a do/while loop around it with 'is correct' as the condition:
do {
...all regular code...
} while(firstAnswer == 'y');

What about:
Console.Clear();
?

you should make functions for this. Put the enter name part in a function then call this function at the start of the Main function and in the if statements.

Related

C# Console - how to set up a countdown timer limtit to user input with readline

I am trying to write a very simple mathematical game in C# Console Application. The program will ask a simple mathematical question to the user. The user must respond by typing the answer and then press enter. I used the code
userinput = Convert.ToInt32(Console.Readline());
code to do this. However, I need the user to assign the value of userinput variable in three seconds after the problem is asked. So, I have to start a countdown timer immediately after the problem is asked. If the user does not type the answer and hit enter within three seconds, the program will display the message "timeout for this question" and immediately display the next question. If the user can type the answer and hit enter within three seconds, the program should immediately stop the countdown timer and evaluate the user's answer. I would be very happy if you can help me with that. Thank you very much in advance.
Note: I read the similar threads but they are based on readykey type user inputs. I need a readline type input.
Some pseudocode:
ask the problem;
start the timer;
if (the user types the answer and presses enter within three seconds)
{
evaluate the answer;
go to the next question;
}
else
{
prompt timeout;
go to the next question;
}
Countdown timers are a great way to add an extra touch of challenge and excitement to any game or activity. In this article, we will provide you with a step-by-step guide on how to set up a countdown timer limit to user input with readline in C# Console.
The first step is to import the C# Console namespace. This will give you access to the readline and Console classes, which are required for setting up a countdown timer. To do this, simply place the following code in your project:
using System;
Next, you need to create a method that will be used to set the timer limit. In this example, we are going to use a loop to count down from the user-specified value to zero. To do this, declare a new integer variable called ‘limit’ and set it to the result of the ReadLine() method. This method will prompt the user to enter a value they want to use as a timer limit:
int limit = int.Parse(Console.ReadLine());
Now, you will need to set up the loop for the countdown. This loop will continue running until it reaches zero. Inside the loop, you can use the Console.WriteLine() method to print out current time left for the user. After each iteration, you need to decrease the value of the limit variable by one:
while (limit > 0)
{
Console.WriteLine("Time left: " + limit);
limit--;
}
Finally, you will need to add some code to print out a message when the timer has reached zero. This can be done by using the Console.WriteLine() method again, this time with a message that informs the user that their time has run out:
if (limit == 0)
{
Console.WriteLine("Time's up!");
}
With that, you have successfully created a countdown timer limit to user input with readline in C# Console! This simple script can be used to add a bit of extra challenge and excitement to any game or activity you create.

C# - Passively checking for key press

I am not using windows forms so this is not a duplicate of Capture keystroke without focus in console. Please remove the duplicate label or direct me somewhere else
So have been away from C# for a long time and trying to get back into it. I am messing with a small console app that requires inputting text from the user. The whole program works fine but now I want to add a check to see if escape is ever pressed.
I originally used ReadKey, but that just checks the current key which has two problems.
1. it uses the key pressed, so strings are missing a character (the one which was checked)
2. it is only in the moment. I want it to be passively waiting until its pressed
What would be the best way to do this?
ex:
I type the string "Hello World!"
If I press the desired key(lets say escape) at any time, I want it to react. Otherwise the string should be entered like normal
edit
example of made up dictionary program (yes, I know there is already a class for this)
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
string entry = Console.ReadLine();
if (!entry.Contains(","))
{
...
}
else
{
...
}
}
Thank you all very much for your time.
Not sure what you're getting at but you can use this to detect if the Escape key was pressed.
if (Console.KeyAvailable)
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
// Do something
}
}
Or alternatively use a loop that breaks when Escape is entered:
var x = Console.ReadKey();
while (x.Key.ToString() != "Escape")
x = Console.ReadKey();

Sum up two steps into one step

In a class in a console application I wrote a method that reads many integer inputs and sums them up. The inputs calls for another method written in another class (Input.ReadIntegerConsole()) that's supposed to read the input, and then make the operations of the first class continue if the input is an integer, or otherwise to write "invalid choice", this way:
private void ReadInputAndSumNumbers()
{
Console.Write("\nNumber you choose? ");
int.TryParse(Console.ReadLine(), out numberChosen);
numberChosen = Input.ReadIntegerConsole();
sum += numberChosen;
etc. The problem is that this way, when I run the application, the console asks: Number you choose? then whatever I input, the program does nothing. At this point I will put another input and only now the ReadIntegerConsole method starts: if it is an integer the operations continue, otherwise the program displays "invalid choice". How to do it so the program does everything in one step instead of two steps, so it reads my input and immediately verifies if it is an integer or not and decides to continue or to display "invalid choice"? How to do it without having to write two inputs? I know for sure that the Input.ReadIntegerConsole code is written correctly and that's why I didn't display it here. I tried writing in many different parts of the class that numberChosen = Input.ReadIntegerConsole() but it has never worked. I tried also writing numberChosen=int.Parse(ConsoleReadLine())=Input.ReadIntegerConsole() but of course it doesn't work.
Console.Write("\nNumber you choose? ");
int.TryParse(Console.ReadLine(), out numberChosen);
numberChosen = Input.ReadIntegerConsole();
sum += numberChosen;
You didn't provide the implementation of Input.ReadIntegerConsole but its a fair guess that it also calls Console.ReadLine and parses it into an int (same as the line above it). So basically, your code is doing:
Print a message
Wait for user input, parse into an int and store in numberChosen
Call Input.ReadIntegerConsole which likely waits for user input, parses it into an int and returns it, and store it in numberChosen
Add the number to sum
So when you input the first number, it does exactly what you think, but Input.ReadIntegerConsole asks for another input and overwrites the original one (hence if you enter junk, it says "invalid value"). This second read from the console explains why the program appears to do nothing, since its waiting for more input.
Removing the manual Console.ReadLine gets rid of the redundant read/parse, which is why it fixed your code. Its not that it works without Console.ReadLine, its that the method you are using hides a call to it.
If you're asking what I think you're asking, I think you want this:
private void ReadInputAndSumNumbers()
{
Console.Write("\nNumber you choose? ");
int numberChosen;
if(int.TryParse(Console.ReadLine(), out numberChosen)) {
sum += numberChosen;
}
else {
Console.WriteLine("Invalid choice.");
}
}
int.TryParse is a method with an out parameter, which means the result of parsing will be assigned to numberChosen. It returns a bool, however: true if successful (string passed is parseable into an int), or false if unsuccessful. So what it's saying is:
If int.TryParse can create an int from the input string, the variable numberChosen has the result stored when the method finishes; add numberChosen to sum.
else, it was unsuccessful, and write "Invalid choice".
Out parameters can get a little confusing, but they're powerful. But if I did a poor job explaining, here are some links: Int32.TryParse, out (C# reference)

C# Console Program issues

I need help in understanding what may be wrong with this simple C# console app program. What I want to do, is perform various arithmetic operations via classes. Here is the program.
static void Main(string[] args)
{
Console.Clear();
Arithmetic a1 = new Arithmetic();
Console.Write("\nEnter the value for first variable\n");
a1.obj1 = Console.Read();
Console.Write("\nEnter the value for the second variable\n");
a1.obj2 = Console.Read();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Apparantley, the program builds and compiles ok, but on the run time it takes the value of the first integer, and without taking the value of the next integer, it writes the last line on the display (Press any key to exit)
Console.Read() reads a single character from standard input, and returns its ASCII value.
If you press two keys, each Console.Read() call will return one of them
You probably want ReadLine(), which reads an entire line of text (which you will then want to parse into an int).

Why Doesn't Read() work as Expected?

I'm using Visual Studio 2008 for C#. I can't understand why this simple code does not work as expected. Any ideas? Thanks!
using System;
namespace TryRead
{
class Program
{
static void Main()
{
int aNumber;
Console.Write("Enter a single character: ");
aNumber = Console.Read(); **//Program waits for [Enter] key. Why?**
Console.WriteLine("The value of the character entered: " + aNumber);
Console.Read(); **//Program does not wait for a key press. Why?**
}
}
}
//Program waits for [Enter] key. Why?
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence).
//Program does not wait for a key
press. Why?
Subsequent calls to the Read method retrieve your input one character at a time [without blocking]. After the final character is retrieved, Read blocks its return again and the cycle repeats.
http://msdn.microsoft.com/en-us/library/system.console.read.aspx
You need to use Console.ReadKey() instead of Console.Read().

Categories

Resources