Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I need to have the program close if bool option = false. The "while (option == false)" statement is at the bottom of the code. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
double numA = 0;
double numB = 0;
double answer = 0;
string functionType;
string aLine;
string bLine;
string next;
bool option = true;
while (option == true)
{
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
switch (functionType)
{
case "V":
Console.WriteLine(" + Addition" + '\n' + " - Subtraction" + '\n' + " * Multiplication" + '\n' + " / Division" + '\n' + " % Percent" + '\n' + " \\ Square Root" + '\n' + " ^ Exponent");
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
break;
case "v":
Console.WriteLine(" + Addition" + '\n' + " - Subtraction" + '\n' + " * Multiplication" + '\n' + " / Division" + '\n' + " % Percent" + '\n' + " \\ Square Root" + '\n' + " ^ Exponent");
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
break;
}
Console.WriteLine("Enter the first number: ");
aLine = Console.ReadLine();
numA = Double.Parse(aLine); Console.WriteLine("Enter the second number: ");
switch (functionType)
{
case "\\":
answer = Math.Sqrt(numA);
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
continue;
break;
case "%":
answer = numA * 100;
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
break;
continue;
}
Console.WriteLine("Enter the second number: ");
bLine = Console.ReadLine();
numB = Double.Parse(bLine);
switch (functionType)
{
case "+":
answer = numA + numB;
break;
case "-":
answer = numA - numB;
break;
case "x":
answer = numA * numB;
break;
case "*":
answer = numA * numB;
break;
case "X":
answer = numA * numB;
break;
case "/":
answer = numA / numB;
break;
case "^":
answer = Math.Pow(numA, numB);
break;
}
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
}
while (option == false)
{
}
}
}
}
Forgive me if this is an easy answer, but I have been learning c# for about 2 hours.
You don't need the while (option == false) loop at the end. What you do need to do, is check the value after each user input, and only proceed if the condition is not met. Ie, after each switch statement:
if (!option)
return;
This will exit from the outer while loop, and then the Main function will exit, thus ending your program.
Related
I am studying programming and I am very beginner (started 2 months ago).
I am doing a c# exercise for maths calculation. Our professor used a if ... else (embricated) loops to do the exercise. I wanted to use a switch case but I am struggling with the local variables.
I understand the issue: case 2 and 3 does not "know" the variables totalNumber and nbrSubAssy is as they come from case 1 and case 2, then they are detected as not assigned.
If I still want to use a switch case, what could I do to solve it?
using System;
namespace Denombrements
{
class Program
{
static long IntMultiplication(int startValue, int endValue)
{
long multiplication = 1;
for (int k = startValue; k <= endValue; k++)
multiplication *= k;
return multiplication;
}
static int UserSelection(String message)
{
int number = 0;
Console.Write(message);
try
{
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine();
Console.WriteLine("Wrong input, enter an integer");
}
return number;
}
static void Main(string[] args)
{
char choice = '1';
while (choice != '0')
{
Console.WriteLine("Permutation ...................... 1");
Console.WriteLine("Arrangement ...................... 2");
Console.WriteLine("Combination ...................... 3");
Console.WriteLine("Quit ............................. 0");
Console.Write("Choice : ");
choice = Console.ReadKey().KeyChar;
Console.WriteLine();
switch(choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
int totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
int nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
long arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
Console.ReadLine();
}
}
}
Declare your variable before While loop and it will keep the value of it for all the life of LOOP and you could access the old values
char choice = '1';
int nbrSubAssy = 0;
int totalNumber = 0;
long arrangement = 0;
while (choice != '0')
{
// code ...
switch (choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
or in my opinion the better solution you could ask for the value in every case you need them
My program works correctly. The only thing I am trying to figure out is how to send an error for invalid user input. If a user types in strings or numbers without using spaces, "a * b", "12*5", how can I send an error in a split.
using System;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
double answer;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
}
else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
}
else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
}
else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
}
}
}
Calculator
Math Operations:
Multiplication: *
Addition: +
Subtraction: -
Division: /
Enter your equation below:
For example: 5 + 5
5*5 //I want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
at System.Double.Parse(String s)
at Calculator1.Program.Main(String[] args)
Press any key to continue . . .
Calculator
Math Operations:
Multiplication: *
Addition: +
Subtraction: -
Division: /
Enter your equation below:
For example: 5 + 5
a * b //I also want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
at System.Double.Parse(String s)
at Calculator1.Program.Main(String[] args)
Press any key to continue . . .
This is probably what you need:
public static void Main(string[] args)
{
double answer;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
try{
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
switch(operation){
case "*":
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
break;
case "/":
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
break;
case "+":
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
break;
case "-":
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
catch(FormatException ex){
Console.WriteLine("You entered a bad operation, try another one");
}
}
}
All you have to do is to catch a format exception that caused by a parse of a double (that isn't really a double). If you catch it, then you print an error message to the user.
I don't know what you mean by "send an error in a split". Split just splits a string.
Validate the input the do a Console.Writeline with your error message.
For validating the user input I suggest using TryParse instead of Parse. This avoids the exceptions and you can check if the input was valid.
And yes. Use a switch statement instead of your if else version. Ctrl-. should offer a refactoring for this.
Kind regards
Bernd
See this solution, please:
// Your codes
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string str = Console.ReadLine().Replace(" ", ""); // Remove all spaces
string[] values = Regex.Split(str, #"([\+\-\*\/])"); // Split numbers and operator and also keep operator
if (values.Length != 3)
{
Console.WriteLine("Expresion is not correct.");
}
else
{
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
switch (operation)
{
case "*":
answer = firstNum * secondNum;
break;
case "/":
answer = firstNum / secondNum;
break;
case "+":
answer = firstNum + secondNum;
break;
case "-":
answer = firstNum - secondNum;
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response.ToUpper() == "YES" || response.ToUpper() == "Y");
}
}
// Your codes
This is some part of the code.
I am getting the error "Control cannot fall through from one case label to another in case 3".
In spite of using the break statement, it is not getting detected. What is the right way to do it?
Update: Error is in case 3. Don't bother to waste your time on other cases.
switch (output)
{
case 1:
int num, reverse = 0;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num / 10;
}
Console.WriteLine("Reverse of Number is : "+reverse);
Console.ReadLine();
break;
case 2:
int number, sum = 0, r,square;
Console.WriteLine("Enter a Number : ");
number = int.Parse(Console.ReadLine());
while (number != 0)
{
r = number % 10;
number = number / 10;
square = r * r;
sum = sum + square;
}
Console.WriteLine("Sum of square of Digits of the Number : "+sum);
Console.ReadLine();
break;
case 3:
Console.WriteLine("Enter 1 for AND 2 for OR and 3 for XOR Operation");
int answer = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your 2 inputs are?");
int inp1= Convert.ToInt32(Console.ReadLine());
int inp2= Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
int input3 = inp1 * inp2;
System.Console.WriteLine("Output is" + input3);
Console.ReadLine();
break;
case 2:
int input4 = inp1 + inp2;
System.Console.WriteLine("Output is" + input4);
Console.ReadLine();
break;
case 3:
if (inp1 == inp2)
{
System.Console.WriteLine("OUTPUT IS 0");
Console.ReadLine();
}
else
{
System.Console.WriteLine("Output is 1");
Console.ReadLine();
}
break;
Your problem is that you only break out of the inner case and not the outer, so you're getting a fall through issue.
case 3 ...
case 3:
if (inp1 == inp2)
{
System.Console.WriteLine("OUTPUT IS 0");
Console.ReadLine();
}
else
{
System.Console.WriteLine("Output is 1");
Console.ReadLine();
}
break;
break; //break the outer case3
Add a goto case X in place of the break for where you want the fall though to occur.
... never mind. you need an expression block on the first case 3.
case 3
{
/// your other switch here
break;
}
By not using scoping blocks you overlooked the outer case statement. It needs break as well as the inner statement.
Okay so I am new to C# and I just wanted to create a simple calculator with the console. My question is how could I make the user chose different values for num1 and num2 when they chose to divide zero, or divide by zero to prevent the program from crashing due to an undefined result. I figured I could use a while loop to check and see if answer results as an int, and if not repeat the entire program. How could I check answer to verify the result is an int?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
int num1;
int num2;
string operand;
float answer;
while ()
{
Console.WriteLine("Please enter the first number.");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter which operator you would like to use(+,-,*,/)");
operand = Console.ReadLine();
Console.WriteLine("Please enter the second number.");
num2 = Convert.ToInt32(Console.ReadLine());
switch (operand)
{
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " + " + num2 + " = " + answer);
Console.ReadKey();
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " - " + num2 + " = " + answer);
Console.ReadKey();
break;
case "*":
answer = num1 * num2;
Console.WriteLine(num1 + " * " + num2 + " = " + answer);
Console.ReadKey();
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("You cannot devide by zero, please select a different number.");
num2 = Convert.ToInt32(Console.ReadLine());
}
else if (num1 == 0)
{
Console.WriteLine("You cannot devide zero, please select a different number.");
num1 = Convert.ToInt32(Console.ReadLine());
}
else
{
answer = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + answer);
Console.ReadKey();
}
break;
}
}
}
}
}
you really only need to check the second value (num2). You'd want to evaluate immediately after the read. How you handle it is up to you. You could loop with a while indefinitely, but you'd also want validate (as with any of these inputs), and give the user an option to quit if they can't understand the directions to input.
A possible solution is using while, see below:
case "/":
while (num2 == 0)
{
Console.WriteLine("You cannot devide by zero, please select a different number.");
num2 = Convert.ToInt32(Console.ReadLine());
}
answer = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + answer);
Console.ReadKey();
break;
However, you should think about change to use int.TryParse method (https://msdn.microsoft.com/en-us/library/system.int32.tryparse%28v=vs.110%29.aspx), as if the user type something that is not a number, Convert.ToInt32 is going to throw a FormatException (https://msdn.microsoft.com/en-us/library/sf1aw27b%28v=vs.110%29.aspx).
I think the cleanset sollution is to extract some methods (select the code and right click with mouse->refactoring->extractMethod).
one of the functions should be "getSecondNumber"
inside that function you start with "enter second number or click "q" to quit.
end you end with if Int.TryParse results with false, or number==0 call your function again (and you'll come to the starting position of "enter second number..."
good luck
using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
switch (action) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-":
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*":
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/":
Console.WriteLine("Result is > ", number1 / number1);
break;
default:
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}
I'm trying to get this switch statement to work but it keeps coming up with error, can't change string to char. I don't see where I have tried to change a string to char.
Use
action = Console.ReadKey().KeyChar;
instead of
action = Console.ReadLine();
&
case "+": to case '+':
you declare
char action;
as a char Type but
switch (action)
{
case "+": // here you compare it with a string.
....
case "-": // here you compare it with a string.
....
case "*": // here you compare it with a string.
....
case "/": // here you compare it with a string.
...
action = Console.ReadLine(); //here you try to set a string
replace char action; with string action;
You may find useful to remove swicth at all and implement a dictionary instead:
Dictionary<String, Func<Double, Double, Double>> Actions = new {
{"+", (x, y) => x + y},
{"-", (x, y) => x - y},
{"*", (x, y) => x * y},
{"/", (x, y) => x / y},
};
...
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
Func<Double, Double, Double> func;
if (Actions.TryGetValue(action, out func))
Console.WriteLine("Result is > ", func(number1, number2));
else
Console.WriteLine("ERROR INVALID INPUT");
if you have a lot of actions (e.g. power **, reminder % etc.) dictionary implemenation is more readable.
using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
var readaction = Console.ReadLine();
string actionString = readaction.ToString();
switch (actionString) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-" :
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*" :
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/" :
Console.WriteLine("Result is > ", number1 / number1);
break;
default :
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}