I am trying to make this console calculator running in loop until the user want to exit the application. How can i use a for loop with if else statements, is it possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Do you want to do an another math operation?");
Console.ReadLine();
}
}
}
You can add a question for user via Console.ReadKey method and then check his answer:
do
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Calculate the next operation (Y/N)?");
}
while(Console.ReadKey(true).Key == ConsoleKey.Y);
So you get the output like in the screenshot below:
Try following. I made the writlines a write :
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
while(true)
{
double sum = 0;
double num1;
Console.Write("First number: (or Exit)");
string firstNumStr = Console.ReadLine();
if(firstNumStr == "Exit") break;
num1 = Convert.ToInt32(firstNumStr);
double num2;
Console.Write("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
}
A for loop is used when you know the (maximum) number of iterations upfront.
In your scenario, a while loop is more apropriate.
do
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
}while( key != ConsoleKey.Q );
or, use an endless while - loop and break from the loop on a certain condition:
while( true )
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
if( key == ConsoleKey.Q )
{
break;
}
}
Related
I'm trying to make a fully functioning calculator application for a school assignment. To do that though I need to use try-catch to handle the DivideByZero error this is my code right now:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
but it's not working. It seems to make my code at the top invalid. Does anybody know how to format it properly?
P.S. Full code here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator_MK._2
{
class Program
{
static void Main(string[] args)
{
Calculator();
}
private static void Calculator()
{
decimal num1;
decimal num2;
string operation;
decimal result;
decimal num3;
decimal num4;
Console.WriteLine("This is IK's Calculator program that should work if you do everything I say");
Console.ReadLine();
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
if (operation == "x")
{
result = num1 * num2;
Console.WriteLine("{0} * {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "/")
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "+")
{
result = num1 + num2;
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "-")
{
result = num1 - num2;
Console.WriteLine("{0} - {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "Fs")
{
int a = 0;
int b = 1;
int c = 1;
Console.WriteLine(a);
Console.WriteLine(b);
for (; c <= 34; c = a + b)
{
Console.WriteLine(c);
a = b;
b = c;
Console.WriteLine();
}
}
if (num2 == 0)
{
Console.WriteLine("Can't divide by zero fool");
}
}
}
}
The try block has to be around the code that causes the exception, in your case this is
result = num1 / num2;
But it would be better to check there for 0 before you call this line and therefore avoid the exception.
The problem you have is that you have declared the try/catch in the wrong place in the application:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
All that is going on here are string to number conversions. There are no mathematical operations that could result in DivideByZeroException exceptions.
Instead, you could wrap the divide operation and anything after it you don't want to run if there is an exception:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch (DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
That said, it is not a good practice to allow exceptions to happen in C# if they can be avoided. In this case, you only need to check the divisor to ensure it is not zero to avoid an exception from occurring.
else if (operation == "/")
{
if (num2 != 0)
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
You have to try the operation itself and not the selection of the operation:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch(DivideByZeroException ex)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
Right now you try to read inputs from the User. If the user inputs something wrong whichc would throw an exception, your try block would trigger but the catch wont, because you are looking for a DivideByZeroException, which wont occur by input
I have a cosole appliction
in this try to set timer that is when question display then timer should be start and when in 10 seconds answer not give then should start next question i want to do this
i am done with
I set 3 conditions first they should type number that how many question want to attemppt then select level then select operator .. so when all question typed i.e.
no of question : 2
level : 1
operator: +
then timer start of 10 seconds and when 10 seconds complete then question is display
where as i want first question display and timer then when question not answered with in 10 seconds then next should start
this is what i do
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int userans;
int computerans;
int numofquestions;
int numofquestionsleft;
int correctanswer = 0;
Console.WriteLine("\t\t OPERATOR OF QUIZ \t\t");
Console.WriteLine("\t\tOperator 1:Addition(+)\t\t");
Console.WriteLine("\t\tOperator 2:Subtarction(-)\t\t");
Console.WriteLine("\t\tLEVELS OF QUIZ\t\t");
Console.WriteLine("\t\tLevel 1 (1-9)\t\t");
Console.WriteLine("\t\tLevel 2 (10-99)\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.WriteLine("\t\tYour quiz start now\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.Write("How many questions do you want to attempt? ");
numofquestions = Convert.ToInt32(Console.ReadLine());
Console.Write("Which level that you want to play? ");
int level = Convert.ToInt32(Console.ReadLine());
Console.Write("which operator do you want to play?");
string opt = Console.ReadLine();
//for (int a = 10; a >= 0; a--)
//{
// Console.SetCursorPosition(0, 2);
// Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
// System.Threading.Thread.Sleep(1000);
//}
numofquestionsleft = numofquestions;
while (numofquestionsleft > 0)
{
if (level == 1)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(1, 10);
int num2 = rnd.Next(1, 10);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(1, 10);
num2 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(1, 10);
int num4 = rnd.Next(1, 10);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(1, 10);
num4 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
if (level == 2)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(10, 99);
int num2 = rnd.Next(10, 99);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(10, 99);
num2 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(10, 99);
int num4 = rnd.Next(10, 99);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(10, 99);
num4 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
//if(numofquestions>)
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(1000);
}
Console.ReadKey();
}
}
}
}
Your code is quite messy. You got everything in a single method. So creating additional method(s), which a timer needs, you cannot access any variable that is important to the timer. You need to start making your own classes. This gives you so much more control over the variables of your program. It is difficult with your code, to put you in the right direction. You need to change so much.
For fun, and some experience as well, I created what you was working on. A calculating game, or test, or w/e you wanna call it. I will share my code with you, in the hope you will learn some things out of it.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Program
{
static void Main(string[] args)
{
// Add different difficulty options
Dictionary<string, Difficulty> DifficultyOptions = new Dictionary<string, Difficulty>();
DifficultyOptions.Add("easy", new EasyDifficulty());
DifficultyOptions.Add("medium", new MediumDifficulty());
DifficultyOptions.Add("hard", new HardDifficulty());
// Add different game options
Dictionary<string, GameType> GameOptions = new Dictionary<string, GameType>();
GameOptions.Add("additive", new GameAdditive());
GameOptions.Add("subtractive", new GameSubtractive());
GameOptions.Add("randomize", new GameRandomize());
// Default game settings at start up
string GameDiff = "easy";
string GameMode = "additive";
Console.WriteLine("Welcome to Verkade's Calculating Game.");
Console.WriteLine("By default game difficulty has been set to " + GameDiff);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of DifficultOptions variable, and display them
foreach (KeyValuePair<string, Difficulty> kvp in DifficultyOptions)
{
Console.WriteLine("/difficulty " + kvp.Key);
}
Console.WriteLine("");
Console.WriteLine("By default game mode has been set to " + GameMode);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of game options and display them
foreach (KeyValuePair<string, GameType> GameTypes in GameOptions)
{
Console.WriteLine("/gamemode " + GameTypes.Key);
}
Console.WriteLine("");
Console.WriteLine("When you're done setting up, type in /start to start the game,");
Console.WriteLine("/stop to stop the game. /exit to stop entirely.");
//This will keep the instance of the game once started
Game CurrentGame = null;
//this will keep the program alive. By typing /exit, it will turn into false, and stops the program.
bool KeepProgramAlive = true;
//This is a loop that keeps on listening to your input
while (KeepProgramAlive)
{
// This will split up the users input, when a space is used.
// This way the first cut will contain /start, /stop, /gamemode, etc. It will be stored as 'UserInput[0]'
// In the second cut, which is 'UserInput[1]', things like 'easy', 'medium', 'hard', 'subtractive', etc will be stored
string[] UserInput = Console.ReadLine().Split(' ');
switch (UserInput[0])
{
case "/exit":
{
KeepProgramAlive = false;
break;
}
case "/start":
{
if (DifficultyOptions.ContainsKey(GameDiff) && GameOptions.ContainsKey(GameMode))
{
Console.WriteLine("Game has been set up. When you're ready, press Enter so you'll get your first question");
CurrentGame = new Game(DifficultyOptions[GameDiff], GameOptions[GameMode]);
}
break;
}
case "/stop":
{
if (CurrentGame != null)
{
CurrentGame.Stop();
CurrentGame = null;
Console.WriteLine("Game has been stopped. You can not change settings and start again if you like.");
}
break;
}
case "/gamemode":
{
// checking the length to see there are 2 values. /gamemode is 1 of them. 'subtractive' is another one.
if (UserInput.Length >= 2)
{
// very important, because i am using a dictionary, i can check whether the gamemode exists or not
if (GameOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed gamemode to " + UserInput[1]);
GameMode = UserInput[1];
}
else
{
Console.WriteLine("That gamemode does not exist");
}
}
break;
}
case "/difficulty":
{
if (UserInput.Length >= 2)
{
if (DifficultyOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed the difficulty to " + UserInput[1]);
GameDiff = UserInput[1];
}
else
{
Console.WriteLine("That difficulty does not exist");
}
}
break;
}
default:
{
// checking if the game has started, and if so, Handler in the game-class will check your input
if (CurrentGame != null)
{
int NumberGiven;
Int32.TryParse(UserInput[0], out NumberGiven);
CurrentGame.Handler(NumberGiven);
}
break;
}
}
}
}
}
}
Operators.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
abstract class GameType
{
public int Answer;
public Random Rnd = new Random();
public abstract string MakeSum(Difficulty Diff);
}
class GameAdditive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
}
class GameSubtractive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
class GameRandomize : GameType
{
public override string MakeSum(Difficulty Diff)
{
int mode = Rnd.Next(0, 2);
if (mode == 0)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
else
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
}
}
Game.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Game
{
Difficulty Game_Diff;
GameType Game_Type;
int TicksRemaining = 0;
int TotalAnswers = 0;
int CorrectAnswers = 0;
int WrongAnswers = 0;
Timer TimerCountdown;
public Game(Difficulty GDiff, GameType GType)
{
Game_Diff = GDiff;
Game_Type = GType;
TimerCountdown = new Timer(100);
TimerCountdown.Elapsed += TimerCD;
TimerCountdown.AutoReset = true;
}
public void Handler(int Answer)
{
if (TicksRemaining > 0)
{
if (Answer == Game_Type.Answer)
{
CorrectAnswers++;
Console.WriteLine("Good job. You got the correct answer.");
}
else
{
WrongAnswers++;
Console.WriteLine("Wrong answer. The answer was " + Game_Type.Answer + ".");
}
TotalAnswers++;
Console.WriteLine("Current score: " + CorrectAnswers + " correct answers out of " + TotalAnswers);
TicksRemaining = 0;
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
else
{
string SumText = Game_Type.MakeSum(Game_Diff);
Console.WriteLine("What is the solution to the sum " + SumText);
TicksRemaining = Game_Diff.Time;
TimerCountdown.Start();
}
}
public void TimerCD(Object source, ElapsedEventArgs e)
{
if(TicksRemaining > 0)
{
TicksRemaining--;
if ((TicksRemaining % 10) == 0)
{
Console.Write(Math.Floor((decimal)(TicksRemaining / 10)) + "...");
}
if (TicksRemaining == 0)
{
WrongAnswers++;
Console.WriteLine("\r\nTime is up. The answer was " + Game_Type.Answer);
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
}
}
public void Stop()
{
TimerCountdown.Stop();
}
}
}
Difficulty.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
// nice thing about abstract classes and child classes are that you can store a 'EasyDifficulty' object under variable-type 'Difficulty'
// this allows me to create a dictionary, with 'Difficulty' type as value, and yet put all the different child classes in there
// another thing you can do, and you can see it under 'Operators.cs' file, is that you can have a method, with the same name in every
// child class, and yet they perform different things.
abstract class Difficulty
{
public int MinNumber = 1;
public int MaxNumber = 1;
// Time in ticks. 1 tick = 100ms. Reason why I made it so is because maybe you want to give the player 7.5 seconds to do the sum
public int Time = 100;
}
class EasyDifficulty : Difficulty
{
public EasyDifficulty()
{
MinNumber = 1;
MaxNumber = 9;
Time = 100;
}
}
class MediumDifficulty : Difficulty
{
public MediumDifficulty()
{
MinNumber = 1;
MaxNumber = 99;
Time = 75;
}
}
class HardDifficulty : Difficulty
{
public HardDifficulty()
{
MinNumber = 1;
MaxNumber = 999;
Time = 50;
}
}
}
Your delay is only 1 second. Increase the delay to 10 seconds by:
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(10000);
}
Queston is answered thanks for the help :)
I made a code with multiple methods in a class but when I try to run it it says
Expected class, delegate, enum, interface, or struct
on the two methods that are not the main methods. I read around and found that someone had the same problem and the case was that the methods weren’t in the class. But couldn't figure out how to fix that. Any tips?
PS: I’m pretty new to coding ;)
using System;
namespace Testing
{
public class Calculator
{
public static void Main (string[] args )
{
string answer;
Console.WriteLine ("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine ());
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
else
{
Console.WriteLine ("Please type multiply or divide.");
goto Start;
}
}
}
public static void DividingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be divided");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a number to divide by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine ("");
Console.ReadKey ();
}
public static void MultiplyingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be multiplied");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a numeber to multiply by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine ("");
Console.ReadKey ();
}
}
}
Working version:
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
while (true)
{
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
break;
}
else if (answer == "divide")
{
DividingMethod();
break;
}
else
{
Console.WriteLine("Please type multiply or divide.");
}
}
}
public static void DividingMethod()
{
Console.Write("Enter a number to be divided");
double num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
double num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01/num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01*num02);
Console.WriteLine("");
Console.ReadKey();
}
Call a method with no parameters like MultiplyingMethod(); instead of MultiplyingMethod;. Thats no valid C#
Please don't use goto. It makes your code messy. Take a look at loops
You should call the methods with ().
Write MultiplyingMethod(); instead of MultiplyingMethod(); and
DividingMethod(); instead of DividingMethod;
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}
else
{
Console.WriteLine("Please type multiply or divide.");
goto Start;
}
}
public static void DividingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be divided");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine("");
Console.ReadKey();
}
In addition, never use goto, it is not good!
There are several issues with this code:
Calling functions should be done with the syntax: funcname(params). So DividingMethod; becomes DividingMethod();
Try not to use goto (it sounds easy but makes your code really hard to read and debug)
Too many brackets
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
Should be:
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}
I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.
So I recently made a calculator as part of my A-Level computing class, and it worked fine then my teacher told me to add a BMI Calculator, which again works fine, however now the issue is the calculator does not run. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello! Type BMI to head to the BMI Calulator");
Console.WriteLine("If you want a calculator -- Here are your commands:");
Console.WriteLine("TIMES - ADD - SUBTRACT - DIVIDE");
string text = Console.ReadLine();
if (text == "BMI")
{
Console.Clear();
Console.WriteLine("Welcome to the BMI Calcualtor! Please enter your height (M)");
string height = Console.ReadLine();
Double height1 = Convert.ToDouble(height);
Double height2 = height1 * height1;
Double heightB = Convert.ToDouble(height2);
Console.Clear();
Console.WriteLine("Please enter your Weight(KG)");
string weight = Console.ReadLine();
int weight1 = Convert.ToInt32(weight);
Double weightA = Convert.ToDouble(weight1);
Double fbmi = weightA / heightB;
Console.WriteLine(fbmi);
if (fbmi < 18.5)
{
Console.WriteLine("UnderWeight");
Console.ReadLine();
}
if (fbmi > 18.5&& fbmi < 25.0)
{
Console.WriteLine("Normal");
Console.ReadLine();
}
if (fbmi > 25.0 && fbmi < 29.9)
{
Console.WriteLine("OverWeight");
Console.ReadLine();
}
if (fbmi > 29.9 && fbmi < 40.0)
{
Console.WriteLine("Obese");
Console.ReadLine();
}
if (fbmi > 40.1)
{
Console.WriteLine("Extremely Obese");
Console.ReadLine();
}
if (text == "TIMES")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA * NumberB);
Console.ReadLine();
}
if (text == "ADD")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA + NumberB);
Console.ReadLine();
}
if (text == "SUBTRACT")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA - NumberB);
Console.ReadLine();
}
if (text == "DIVIDE")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA / NumberB);
Console.ReadLine();
}
}
}
}
}
So, any help is appreciated :)
It looks like your { } are a bit out of place:
You should add a } after:
if (fbmi > 40.1)
{
Console.WriteLine("Extremely Obese");
Console.ReadLine();
}
Then remove one from the very end.
Then way it is laid out now, your other if statments are within the if statement for BMI.