I'm writing a grade calculator, and at the end, I ask the user if they have another grade to calculate.
Console.Write("Do you have another grade to calculate? ");
moreGradesToCalculate = Console.ReadLine();
moreGradesToCalculate = moreGradesToCalculate.ToUpper();
I want to display a dialog box with the options of Yes or No.
I want to be able to run the program again, if the DialogResult is Yes, and do something else if the result is No.
You should use a do...while(...) loop.
I think it's not a good idea to run the whole program again, just start over getting numbers for calculating the grades (wrap your code in a loop).
For the DialogBox, simply import System.Window.Forms assembly and use this:
DialogResult result = MessageBox.Show("Do you want to start over?", "Question", MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
// TODO: Exit the program
}
you can use do/while construct like
do {
Console.Write("Do you have another grade to calculate Y/N? ");
var moreGradesToCalculate = Console.ReadLine().ToUpper();
if(moreGradesToCalculate == "Y")
//do something
else if(moreGradesToCalculate == "N")
break;
}while(true);
If you want a dialog box, you'll have to add a reference to System.Windows.Forms and also add a using statement for the same namespace at the top of your file. Then you just have to check the result of calling the Show method on the MessageBox object at the end of a Do-While loop. For example:
do
{
// Grading calculation work...
}
while (MessageBox.Show("Do you have another grade to calculate?",
"Continue Grading?", MessageBoxButtons.YesNo) == DialogResult.Yes);
This will keep looping until the user clicks No.
If you don't want to keep using the mouse, do it all on the command line with this:
ConsoleKeyInfo key = new ConsoleKeyInfo();
do
{
// Grading work...
Console.WriteLine("\nDo you want to input more grades? (Y/N)");
do
{
key = Console.ReadKey();
}
while (key.Key != ConsoleKey.Y && key.Key != ConsoleKey.N);
}
while (key.Key == ConsoleKey.Y);
Here's a link to the reference material on looping - or 'Iteration Statements' from Microsoft. The Do-While is one of a few you should try to learn off by heart when you're just starting out:
http://msdn.microsoft.com/en-us/library/32dbftby.aspx
Related
Right now my problem is getting choice 2 to save and rewrite what was written in choice 1.
Choice 3 should then reset everything.
Right now i tried with at if inside an if and still not getting it to work.
while (true)
{
Console.WriteLine("\tWelcome to my program"); // Makes the user select a choice
Console.WriteLine("[1] To write");
Console.WriteLine("[2] To see what you wrote");
Console.WriteLine("[3] Reset");
Console.WriteLine("[4] End");
string choice = Console.ReadLine();
string typed = ("");
if (choice == "1") // If 1 program asks for text
{
Console.WriteLine("Thank you for your choice, input text");
typed = Console.ReadLine();
}
else if (choice == "2") // Is supposed to say "You wrote, and what user wrote"
{
Console.WriteLine(typed);
}
else if (choice == "3") // Resets the text so if 2 is selected it would say "You wrote, "
{
Console.WriteLine("Reset. Would you like to try again?");
typed = "";
}
else if (choice == "4") // Ends program
{
break;
}
else
{
Console.WriteLine("Input not computing, try again");
}
Your issue is as follows.
First, you are looping your entire program through a while (true) loop. Once the user choice is made, the program will go back to the while (true). Note also that string typed is defined inside the loop. Therefore, every time the loop is called (which is every choice made), the program resets the value of 'typed'.
To fix this, introduce string typed outside the loop.
string typed = "";
while (true)
{
//choices and stuff goes back here
}
Edit: I noticed this comment of yours //Is supposed to say "You wrote, and what user wrote on choice 2. Note that your code in choice 2 won't output "You wrote" + typed. To correct that, change Console.WriteLine(typed); to Console.WriteLine("You wrote, " + typed);.
I'm a newbie and as an exercise, have to create an application that will allow the user 3 attempts to enter their pin correctly. The issue I am having is that once the correct pin is entered, the application shuts down. The same happens after the third attempt. So the "Correct Pin" and "Goodbye" don't actually print out first. Here's what I have at the moment. Thanks.
int pin = 2456;
int attempts = 1;
bool correctPin = false;
while (attempts <= 3 && correctPin == false)
{
//Ask user to enter pin
Console.WriteLine("Please enter your pin");
//read what user types
string guess = Console.ReadLine();
int number1 = int.Parse(guess);
attempts++;
//if correct pin entered
if (number1 == pin)
{
correctPin = true;
Console.WriteLine("Correct Pin");
}
//if incorrect pin entered
else if (number1 != pin)
{
Console.WriteLine("Incorrect Pin");
}
else if (attempts > 3)
{
Console.WriteLine("Goodbye");
}
}
}
}
}
Outside the loop you can put a:
Console.ReadLine();
statement to prevent the program from exiting
It would be good, however, to at least give the user a clue that the application is waiting by writing something like "Press Enter to Exit..." to the console
The console window is closing since there is nothing else left to do. You should put Console.Readline() at the end.
Also, you should put Console.WriteLine("Goodbye"); out of the if statement, just above the Readline().
I was making a calculator in C#. Here is the multiplication part---
using System;
static class calculator
{
public static void Main()
{
welcome:
Console.WriteLine("Welcome to my calculator, please press enter to continue");
Console.ReadLine();
Console.WriteLine("Do you want to add, subtract, multiply or divide?");
string x = Convert.ToString(Console.ReadLine());
if (x == "multiply")
{
Console.WriteLine("Please enter the first value");
decimal value1multiply = Convert.ToDecimal( Console.ReadLine());
Console.WriteLine("Please enter the second value" );
decimal value2multiply = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("Result =");
Console.WriteLine(value1multiply * value2multiply);
Console.WriteLine("Thank you for using my calculator!Do you still want to use it?Please answer in 'yes' or 'no' and press 'enter'");
Console.ReadLine();
string yesorno =Console.ReadLine();
if (yesorno == "yes")
{
goto welcome;
}
if (yesorno == "no")
{
Environment.Exit(0);
}
}
}
}
When I type 'yes' when it asks me to, the console should lead me to welcome. But instead, it does not lead me anywhere and remains blank. When I press enter again, the console closes. Why is this happening and how can I prevent it?
What I have tried:
I tried removing the environment.exit(0), thinking that the console was leading me to that but it did not help. I even tried typing the code in Visual Studio, but no difference in the outcome. (I use sharp develop)
Besides the use of goto, which is often frowned upon, you are using one too much ReadLine call.
Here:
Console.ReadLine();
string yesorno = Console.ReadLine();
Maybe you typed yes and then hit Enter twice. In that case yesorno would be empty and your check would fail. The first entry is swallowed by the first ReadLine that didn't got assigned to a variable.
I'm doing a small c# application.
(Press 0 to end the program)
All I know is:
Console.ReadKey(); but that only works when you press ANY key.
But how do you exit an application with just 0?
you don't need to run the while loop to findout the key.
you have to compare with the what ever users enters the key.
ConsoleKeyInfo info= Console.ReadKey();
if (info.KeyChar == 48)
Environment.Exit(0);
else
{ // do your things
}
First of all your program will run in a while loop. Read the entered word and check in if condition that whenever it is 0 or not. If it is 0 then let the program finish by breaking the loop otherwise use continue. Let me know if you have any confusion.
You can use while loop :
ConsoleKeyInfo cki = new ConsoleKeyInfo();
while (cki.Key != ConsoleKey.D0 && cki.Key != ConsoleKey.NumPad0)
{
cki = Console.ReadKey(true);
// your code here
}
I have been searching the web for about an hour and I just can't find the answer to my question. I'm very new to programming and I hope I'm not wasting your time. I want my program to loop if I would click "Y", exit if I click "N" and do nothing if I click any other button. Cheers!
Console.Write("Do you wan't to search again? (Y/N)?");
if (Console.ReadKey() = "y")
{
Console.Clear();
}
else if (Console.ReadKey() = "n")
{
break;
}
You have an example here of Console.ReadKey method :
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
//Get the key
var cki = Console.ReadKey();
if(cki.Key.ToString() == "y"){
//do Something
}else{
//do something
}
You are missing keystrokes this way. Store the return of Readkey so you can split it out.
Also, comparison in C# is done with == and char constants use single quotes (').
ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;
if (key == 'y')
{
Console.Clear();
}
else if (key == 'n')
{
break;
}
you can use the keychar to check that character is pressed
Use can understand that by following example
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}
Presumably by "do nothing" you intend that the user be asked to try pressing a valid key until they do. You can use a do statement (a.k.a. do loop) to repeat some code while some condition is true, for example:
var validKey = false;
var searchAgain = false;
do
{
Console.Write("Do you want to search again? (Y/N): ");
string key = Console.ReadKey().KeyChar.ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine();
if (key == "y")
{
validKey = true;
searchAgain = true;
}
else if (key == "n")
{
validKey = true;
searchAgain = false;
}
else
{
Console.WriteLine("Please press the 'Y' key or the 'N' key.");
}
} while (!validKey);
// Now do something depending on the value of searchAgain.
I used the "not" in !validKey because it reads better that way: do {this code} while (the user hasn't pressed a valid key). You might prefer to use a while loop if you think the code reads better with that construction.
The .ToLower(System.Globalization.CultureInfo.InvariantCulture) bit is so that it doesn't matter if "y" or "Y" is pressed, and it has a very good chance of working with any letter, even the ones that have unexpected upper/lower case variations; see Internationalization for Turkish:
Dotted and Dotless Letter "I" and What's Wrong With Turkey? for explanation of why it's a good idea to be careful about that kind of thing.