How to prompt the user to continue? - c#

I want to ask the user if they want to continue adding two numbers, so if they type Y it would start again if N it will exit.
I'm not sure if I should use if/else or while (or both!) or something else.
Here is what I have so far:
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.Write("Do You want to add more numbers? Y / N");
Console.ReadLine();
How can I finish it?

First, let's extract method ReadInt (why should you repeat yourself?):
private static int ReadInt(string title) {
// keep asking user until correct value provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
// If we can parse user input as integer...
if (int.TryParse(Console.ReadLine(), out int result))
return result; // .. we return it
Console.WriteLine("Syntax error. Please, try again");
}
}
Main code: Here, you can wrap the code fragment into do {...} while (since you want the loop to be performed at least once)
do {
int num1 = ReadInt("Enter a number to add: ");
int num2 = ReadInt("Enter another number to add: ");
// (long) num1 - we prevent integer overflow (if num1 and num2 are large)
Console.WriteLine($" {num1} + {num2} = {(long)num1 + num2}");
Console.WriteLine("Do You want to add more numbers? Y / N");
}
while(Console.ReadKey().Key == ConsoleKey.Y);

while (true)
{
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.WriteLine("Do You want to add more numbers? Y / N");
string YesOrNo = Console.ReadLine();
if (YesOrNo == "N")
{
break;
}
}
You need a loop the most common that I see for a scenario like this is the while loop. You also however need a break condition so that the while loop ends an if statement is one way you could break out like in my example above. The break is reached if the user enters N into the console.
Note my example will continue to run if anything other than N is typed into the console.

Related

Write a method GetAverage() to read 3 numbers from keyboard and return their average

I have tried to write the code, for this task, but I am getting an error with my 'ReadLine'.
class Program
{
static void Main(string[] args)
{
double average = GetAverage();
Console.WriteLine("The average of the numbers is: " + average);
}
public static double GetAverage()
{
double num1 = double.Parse(Console.ReadLine("Enter the first number: "));
double num2 = double.Parse(Console.ReadLine("Enter the second number: "));
double num3 = double.Parse(Console.ReadLine("Enter the third number: "));
return (num1 + num2 + num3) / 3;
}
}
The Console.ReadLine() does not accept any argument. It read data from the console and return an string.
You should use Console.WriteLine for printing data on console screen and use Console.ReadLine to getting data from console :
public static double GetAverage()
{
Console.WriteLine("Enter the first number: ");
double num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
double num2 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the third number: ");
double num3 = double.Parse(Console.ReadLine());
return (num1 + num2 + num3) / 3;
}

Code is working unexpectedly in c# using visual studio code

I am a beginner in c# and I want to create a simple calculator.
I have written all the code and it is not showing any errors, however, it is not showing it correctly.
This is all the code I am using:
using System;
namespace C_
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Calculator";
float num1;
float num2;
float resultSum;
float resultSub;
float resultProd;
float resultDiv;
Console.Write("Enter your first number ");
num1 = Convert.ToInt32(Console.Read());
num2 = Convert.ToInt32(Console.Read());
resultSum = num1 + num2;
Console.Write("The sum is " + resultSum);
resultSub = num1 - num2;
Console.Write("The differnce is " + resultSub);
resultProd = num1 * num2;
Console.Write("The product is " + resultProd);
resultDiv = num1 / num2;
Console.Write("The quotient is " + resultDiv);
Console.ReadKey();
}
}
}
When I run this without debugging,
the console shows this:
https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=netcore-3.1
If you replace Console.Write... with Console.WriteLine..., it will add line breaks to the ends of your print statements, so your output should look like:
The sum is 63
The difference is 37
...
Not sure if I would use float for the type. Especially since you are converting to int32. I have put some different techniques into your program. Since you are just learning these are good things to know. I have provided explanations in the comments of the code.
static void Main(string[] args)
{
Console.Title = "Calculator";
// No need to put the type multiple times
// Just use a comma to separate the names
int num1, num2, resultSum, resultSub, resultProd, resultDiv;
Console.WriteLine("Enter your first number:");
// This is just a label
Num1Entry:
try
{
num1 = Convert.ToInt32(Console.ReadLine());
}
// This exception is for when you don't get a number from the user. i.e. num1 = a
catch (FormatException)
{
Console.WriteLine("Not a number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num1
goto Num1Entry;
}
// This exception is for when the number is out of range for the data type. i.e. num1 = 2147483648 is too big for an int data type.
catch (OverflowException)
{
Console.WriteLine("Invalid number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num1
goto Num1Entry;
}
Console.WriteLine("Enter your second number:");
// This is just a label
Num2Entry:
try
{
num2 = Convert.ToInt32(Console.ReadLine());
}
// This exception is for when you don't get a number from the user. i.e. num2 = a
catch (FormatException)
{
Console.WriteLine("Not a number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num2
goto Num2Entry;
}
// This exception is for when the number is out of range for the data type. i.e. num2 = 2147483648 is too big for an int data type.
catch (OverflowException)
{
Console.WriteLine("Invalid number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num2
goto Num2Entry;
}
resultSum = num1 + num2;
Console.WriteLine("The sum is " + resultSum);
resultSub = num1 - num2;
Console.WriteLine("The differnce is " + resultSub);
resultProd = num1 * num2;
Console.WriteLine("The product is " + resultProd);
// if num2 = 0 you will get an exception.
// Use a try-catch to keep your program from failing.
try
{
resultDiv = num1 / num2;
Console.WriteLine("The quotient is " + resultDiv);
}
catch (DivideByZeroException)
{
Console.WriteLine("You cannot divide by 0");
}
Console.ReadKey();
}
Your code uses the consolekey values, not the numeric value that you entered. The consolekey for 2 is 50. The consolekey for return is 13.

How to start over with my code? C# Console [duplicate]

This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);

C# 'Unassigned local variable'?

I tried to make a piece of code which would roll a dice in the end to decide which character wins and it keeps on saying that there are errors (Use of unassigned local variable 'skillmodifier') & (Use of unassigned local variable 'strengthmodifier'). I would really appreciate any help. P.S I have only been doing programming for a short period of time on Visual Studio 2010. Please help me find a solution to this problem, the problem occurs because I use the variables 'strengthmodifier' and 'skillmodifier' twice. Thank you, yours faithfully, Vikash.
I will paste the task breif below and the code after that:
Task 3 Determining the outcome of an encounter
When there is an encounter between two characters the outcome is determined by the following
process:
• The differences between the strength attributes for the two characters is calculated
• This difference is divided by 5 and then rounded down to create a ‘strength modifier’
• The process is repeated for the skill attribute to create a ‘skill modifier’
• Each player throws a 6 sided dice.
• If the scores on both dice are the same, no changes are made
• If the scores are not the same, the player with the highest score adds the ‘strength
modifier’ to the strength value and the ‘skill modifier’ to the skill value for their
character
• The player with the lower score on the dice subtracts these modifiers from the
strength and skill values for their character
• If a skill value becomes negative, then it is stored as zero
• If a strength value becomes zero or negative, then the character dies.
The program should:
*• Allow the user to input the strength and skill for two characters.
• Display the outcome of the encounter using the process above.
Design an algorithm to describe this process. Write, test and evaluate the code.*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task3
{
class Program
{
static void loopfsto()
{
Console.WriteLine("Please enter a value of strength, and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
}
static void loopfsko()
{
Console.WriteLine("Please enter a value of skill, and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
}
static void loopfstt()
{
Console.WriteLine("Please enter a value of strength for, and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
}
static void loopfskt()
{
Console.WriteLine("Please enter a value of skill for, and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
}
static void Main(string[] args)
{
string Character1;
string Character2;
int strengthmodifiertoround;
int skillmodifiertoround;
int strengthmodifier;
int skillmodifier;
Console.Title = "Strength and Skill";
Console.WriteLine("Welcome to Strength and Skill, please press enter to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a name for character 1, then press enter.");
Character1 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a name for character 2, then press enter.");
Character2 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character1 + ", and then press enter");
string csto = Console.ReadLine(); // Read string from console
int csto1;
if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csto1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsto();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character1 + ", and then press enter");
string csko = Console.ReadLine(); // Read string from console
int csko1;
if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + csko1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfsko();
}
Console.Clear();
Console.WriteLine(Character1 + " has a strength of " + csto1 + " and a skill of " + csko1 + ".");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Please enter a value of strength for " + Character2 + ", and then press enter");
string cstt = Console.ReadLine(); // Read string from console
int cstt1;
if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cstt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfstt();
}
Console.Clear();
Console.WriteLine("Please enter a value of skill for " + Character2 + ", and then press enter");
string cskt = Console.ReadLine(); // Read string from console
int cskt1;
if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
{
Console.WriteLine("Your chosen number is " + cskt1 + ".");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Not an integer!");
Console.ReadKey();
Console.Clear();
loopfskt();
}
Console.Clear();
Console.WriteLine(Character2 + " has a strength of " + cstt1 + " and a skill of " + cskt1 + ".");
Console.ReadKey();
Console.Clear();
//--- Finds out if strength for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called strengthmodifier ---//
{
if (csto1 < cstt1)
{
strengthmodifiertoround = cstt1 - csto1;
strengthmodifier = strengthmodifiertoround / 5;
}
if (cstt1 < csto1)
{
strengthmodifiertoround = csto1 - cstt1;
strengthmodifier = strengthmodifiertoround / 5;
}
}
//--- Finds out if skill for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called skillmodifier ---//
{
if (csko1 < cskt1)
{
skillmodifiertoround = cskt1 - csko1;
skillmodifier = skillmodifiertoround / 5;
}
if (cskt1 < csko1)
{
skillmodifiertoround = csko1 - cskt1;
skillmodifier = skillmodifiertoround / 5;
}
}
//--- Tells user to put input and roll a virtual dice (which is actually creating a number between 1 and 6) ---//
Console.WriteLine(Character1 + ", please press enter to roll dice");
Console.ReadKey();
Random rand = new Random();
int character1RandomNumber = rand.Next(1, 6);
Console.WriteLine(Character2 + ", please press enter to roll dice");
Console.ReadKey();
Random rand1 = new Random();
int character2RandomNumber = rand1.Next(1, 6);
Console.WriteLine(Character1 + " rolled a " + character1RandomNumber + " and " + Character2 + " rolled a " + character2RandomNumber + ".");
Console.ReadKey();
if (character1RandomNumber < character2RandomNumber)
{
int char2st = cstt1 + strengthmodifier;
int char2sk = cskt1 + skillmodifier;
int char1st = csto1 - strengthmodifier;
int char1sk = csko1 - skillmodifier;
}
if (character2RandomNumber < character1RandomNumber)
{
}
int ch2st = cstt1 - strengthmodifier;
int ch2sk = cskt1 - skillmodifier;
int ch1st = csto1 + strengthmodifier;
int ch1sk = csko1 + skillmodifier;
}
}
}
Actually, i think your problem is because skillmodifier and strengthmodifier do not get assigned values on all code paths. ie. They are only assigned values from within if clauses and visual studio cannot determine whether or not they are assigned for all possible outcomes. This warning shouldn't stop your code compiling but if you want it to go away you can do something like
int skillmodifiertoround = 0;
instead of just
int skillmodifiertoround;
Now skillmodifiertoround is given a value on declaration.
Edit: "This warning shouldn't stop your code compiling" - Apparently it will stop the program from compiling correctly in c# but the same error in vb only gives a warning but still compiles.
Its rather simple really
int skillmodifier;
You need to assign it - that is give it a value, even a default one - before you can use it. Otherwise the program doesn't know what value it has.
So something like
int skillmodifier = -1;
will fix it for you.
When you declare int skillmodifier declare it as whatever the default value should be,e.g. int skillmodifier = 0;
Do the same for strengthmodifier and you should be good to go!
The problem is that the compiler can detect a way of executing your code without these parameters being set.
Local variables in C# must be initialized before they are used.
From MSDN
Also see related questio Why aren't unassigned local variables automatically initialized?
For generics where type is not known, use default keyword
I think the other people have given you the answer, but I spotted something else.
Instead of
//method
if(tryparse)
{
//done
}
else
//loop
you should turn the methods into methods that return ints and then...
int csko = loopCsko()

C# adding methods and checking to see if numbers have been added

have a small program im playing with. need to make sure it checks if number, if not loop untill their is a number on each input and create a main method and calculator method any help?
code is here /////////////////////////////////////////////////////
int num1;
int num2;
string operand;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
if (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
}
else
{
}
//// enter operand ////
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
if (!eff)
do
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
}
while (eff == true);
{
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
"+ answer.ToString());
Console.ReadLine();
}
}
}
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
" + answer.ToString());
Console.ReadLine();
If this is all you need and you are using a Console App, you can use:
int num1;
int num2;
string operand = string.Empty;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
while (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
res = int.TryParse(text1, out num1);
}
//// enter operand ////
while (operand == string.Empty || operand.Length > 1 || !(new char[] { '+', '-', '*', '/' }).Contains(char.Parse(operand)))
{
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
}
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
while (!eff)
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
eff = int.TryParse(text1, out num2);
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Divide By Zero Error");
return;
}
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " = "+ answer.ToString());
Console.ReadLine();
Why do you need to create a separate method for something so simple. And I found this too simple to be asked, so just asking if this is what was required? You could have struggled a bit more and written this yourself. There is nothing trivial in this. I am just assuming that you are new to programming.
the problem appears to be with the handling of "eff" and "res". If the user keys a non integer value the first time they're asked it doesn't matter what they answer the second time as num1 and num2 aren't populated with the value. Fix that and the code appears to work.
As entering the values appears to be doing the same thing but with a slightly different prompt you should move this into a seperate function, something like this:
static int GetNumberFromUser(string order)
{
string userText = String.Empty;
int result;
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
while (!int.TryParse(userText, out result))
{
Console.WriteLine("FAILED");
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
}
return result;
}
You would then call it by calling
num1 = GetNumberFromUser("first");
num2 = GetNumberFromUser("second");
This function takes care of converting to a number and keeps asking until the user keys in a valid value.
The "Calculator" method would just be copied and pasting the switch you have into a seperate method:
static float Calculator(int num1, string operand, int num2)
{
switch (operand)
{
case "-":
return num1 - num2;
case "+":
return num1 + num2;
case "/":
return num1 / num2;
case "*":
return num1 * num2;
default:
return 0;
}
}
Called using
answer = Calculator(num1, operand, num2);
Whilst I'm at it, the result line is difficult to read, I'd go for something like this
Console.WriteLine("{0} {1} {2} = {3}", num1, operand, num2, answer);

Categories