C# FormatException error [duplicate] - c#

I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong? I am supposed to make this console program as homework to learn about loops, but I am finding out more about other things. It is supposed to keep a running tab of salesperson's commission based a a 10% commission of each sale. Anyways, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}

I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong?
The Convert.ToDouble method will raise a FormatException if the string (returned from Console.ReadLine()) is not a valid number.
Typically, if you want to parse user input, it's a better idea to use Double.TryParse instead, as this lets you determine whether the input was a valid number without catching the exception.
This would normally look something like:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately

While Reed's answers is great, it's not the problem here.
What really happens is the same situation as this one
Console.Read only read the "Second part of the carriage return" and returns "". This is why the Convert fails.
replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine());

Replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());

Related

How to repeat the question until you get the correct answer C#?

I am a beginner in C# and I am currently writing an ATM console where customer:
1 - Check Account Balance
2 - Withdraw Money
3 - Paying In
4 - Press Q to exit
I got stuck at the second option because if the user enters a higher amount than the account balance, I would like C# to repeat the question until it gets a valid reply from the user. I used do-while loop but I still haven't managed to get it right
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ATM
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Barclays, please choose one of the options",
"/n 1 - Check Account Balance",
"/n 2 - Withdraw Money" +
"/n 3 - Paying In" +
"/n 4 - Press Q to exit");
string optionChosen = Console.ReadLine();
int customerBalance = 5000;
switch (optionChosen)
{
case "1":
Console.WriteLine("Your balance is " + customerBalance);
break;
case "2":
Console.WriteLine("Please enter the amount you would like withdraw: ");
int amountEntered = Convert.ToInt32(Console.ReadLine());
if(amountEntered > customerBalance)
do
{
Console.WriteLine("Insufficent balance please enter another amount: ");
amountEntered++;
}while(amountEntered < 5);
else
{
Console.WriteLine("Your new balance is " + (customerBalance - amountEntered));
}
break;
case "3":
Console.WriteLine("Pleas enter the amount you would like to pay in: ");
int amountPaidIn = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your new balance is " + (customerBalance + amountPaidIn));
break;
case "4":
Console.WriteLine("Thank you, have a nice day");
break;
default:
Console.WriteLine("Please enter a valid name");
break;
}
Console.ReadKey();
}
}
}
Here is one solution.
You need to loop across the whole case statement logic. I'm also not sure what use amountEntered++ is? So I have used a boolean to detect whether the amount is valid and used that as the condition in the do while loop.
case "2":
bool validAmount = true;
do
{
Console.WriteLine("Please enter the amount you would like withdraw: ");
int amountEntered = Convert.ToInt32(Console.ReadLine());
if(amountEntered > customerBalance)
{
Console.WriteLine("Insufficient balance - please enter another amount:");
validAmount = false;
}
else
{
Console.WriteLine("Your new balance is " + (customerBalance - amountEntered));
}
} while(!validAmount);
break;

Can someone explain to me what's wrong with my code please?

I've been learning C# and now I'm trying to create a calculator that reads your inputs to learn how to read inputs correctly. If it's really simple I'm sorry I'm new to this.
The error says that it can't convert int to string on (10,20) and (14,20).
using System;
class Calculator {
static void Main() {
int n1, n2;
string operation;
Console.Write("First number: ");
n1 = int.Parse(Console.Read());
Console.Write("Operation: ");
operation = Console.ReadLine();
Console.Write("Second number: ");
n2 = int.Parse(Console.Read());
if (operation == "+") {
Console.Write(n1 + n2);
}else if (operation == "-") {
Console.Write(n1 - n2);
}else if (operation == "*") {
Console.Write(n1 * n2);
}else if (operation == "/") {
Console.Write(n1 / n2);
};
}
} ```
Make all your calls Console.ReadLine() not Console.Read()
Make sure you type an integer for the operands. If you're not typing an integer (I couldn't decide if your 10,20 means your operands are ten and twenty or if you're from a country that uses comma as a decimal separator and 10,20 is ten-and-a-fifth) then you won't succeed in parsing a decimal number with int.Parse, try decimal.Parse instead and change all your data types
Using Console.Read() will read a single character and return its numeric value, so eg a 1 character has an int value of 31 (take a look at an ascii table) which will be very confusing, and even more confusing how A (ascii Value 65) can be added to B (66 - result 131) :) ...
Try with dot. 10.20 and 14.20.
Also try ReadLine
Try this as a starter for 10. There are ways to do it more efficiently I'm sure, but this should give you some ideas:
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("First Number: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Operation: ");
string operation = Console.ReadLine();
Console.Write("Second number: ");
int b = int.Parse(Console.ReadLine());
switch(operation)
{
case "+":
Console.WriteLine(string.Format("Result: {0}", (a + b)));
break;
case "-":
Console.WriteLine(string.Format("Result: {0}", (a - b)));
break;
case "*":
Console.WriteLine(string.Format("Result: {0}", (a * b)));
break;
case "/":
Console.WriteLine(string.Format("Result: {0}", (a / b)));
break;
}
Console.WriteLine("Press any key to close...");
Console.ReadKey();
}
}
}

How to press enter for a menu without the enter being used for the next operation

So, I am learning C#, and to practice, I have been trying to make a math solver, so the way I did it, is 1- I present the math question, 2- I receive user-input of the solution, 3- I compare the user's answer to my answer using an if statement, now, I am trying to add a console menu to add different divisions (multiplication/division/sub./add.), i have successfully added the menu, however I am not able to move onto inputting the numbers, the error I get is http://prntscr.com/ohru2i, how can I fix it?
I have tried putting Console.clear(), I have also tried to use break;, but none of them worked
using Figgle;
using System;
using System.Threading;
public class MainClass
{
public static void Main()
{
Console.Title = $"The Math Solver | Correct = 0 | Wrong = 0";
char choice;
for (; ; )
{
do
{
Console.WriteLine("Choose Method:");
Console.WriteLine(" 1. Multiplication");
Console.WriteLine(" 2. Division");
Console.WriteLine(" 3. Addition");
Console.WriteLine(" 4. Subtraction");
Console.WriteLine(" 5. Find the Remainder");
Console.WriteLine("Press Q to Exit ");
do
{
choice = (char)Console.Read();
} while (choice == '\n' | choice == '\r');
} while (choice < '1' | choice > '5' & choice != 'q');
if (choice == 'q') break;
Console.WriteLine("\n");
Console.Clear();
switch (choice)
{
case '1':
{
Console.WriteLine(
FiggleFonts.Standard.Render("Multiplication"));
int milliseconds2 = 2000;
Thread.Sleep(milliseconds2);
int correctAnswers = 0;
int WrongAnswers = 0;
int Number1;
int Number2;
int myInt2;
while (true)
{
Console.WriteLine("Write the first number to multiply");
Number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Write the second number to multiply");
Number2 = int.Parse(Console.ReadLine());
Console.WriteLine($"Write the answer of {Number1} * {Number2}");
myInt2 = int.Parse(Console.ReadLine());
if (myInt2 == Number1 * Number2)
{
Console.WriteLine(
FiggleFonts.Standard.Render("Correct!"));
correctAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
else
{
Console.WriteLine(
FiggleFonts.Standard.Render("Wrong"));
WrongAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
int milliseconds3 = 2000;
Thread.Sleep(milliseconds3);
Console.Clear();
}
}
}
}
}
The error message I get is http://prntscr.com/ohru2i
You're getting the error when converting a number to a string because console.Read() consumes the first character from the standard input, but leaves the line break from the user hitting enter. Therefore, the next time you go to read a line from the console, you just get a blank line, which is not a valid string for number conversion.
Solution is to use Console.ReadLine() and either look at the first character by indexing the string, or replace choice character constants with string constants.

When Input Values To My Program, It Crashes :( C# [duplicate]

This question already has answers here:
What's the main difference between int.Parse() and Convert.ToInt32
(13 answers)
Closed 4 years ago.
This is the program. Can someone tell me what I did wrong? Every time I input a value for the string SolvingFor, the program crashes. I'm new to coding so if I made a stupid mistake please tell me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PercentageCalculator
{
class Program
{
static void Main(string[] args)
{
string SolvingFor;
int part;
int whole;
int percent;
Console.WriteLine("please only use numbers and lowercase letters.");
Console.WriteLine("Are you trying to solve for percent, part, or whole?");
SolvingFor = Convert.ToString(Console.Read());
if (SolvingFor == "part") {
Console.WriteLine("Please Enter Value of the Whole");
whole = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (whole * percent) / 100); }
else if (SolvingFor == "whole")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / percent);
}
else if (SolvingFor == "percent")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the whole");
whole = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / whole);
}
else
{
Console.WriteLine("Please only input valid lowercase letters and numbers. ");
};
Console.Read();
}
}
}
//SolvingFor = Convert.ToString(Console.Read());
SolvingFor = Convert.ToString(Console.ReadLine());
if you put(hover) the mouse over ReadLine
you will see that it returns a string so Convert.ToString is not needed
SolvingFor = Console.ReadLine();
First Issue:
Below line from your code is reading just one character.
Instead of Console.Read(), use Console.ReadLine() to enable you to input multiple characters.
SolvingFor = Convert.ToString(Console.Read());
Second Issue:
You are using Convert.ToInt32(Console.Readline());
Please note that Convert.ToInt32 will throw an exception in anything apart from number is provided as input.
Better use int.TryParse which returns if the conversion is successful or not.

c# switch loop, adding up total for each case

I have 2 codes that I want to combine into 1 and am having a lot of trouble doing it. The code should ask for the group number then their donation amount and loop back until they press 0. Once they press 0 it should show the total for all groups. Here are the 2 different codes
code 1
using System;
public class TotalPurchase
{
public static void Main()
{
double donation;
double total = 0;
string inputString;
const double QUIT = 0;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
while(donation != QUIT)
{
total += donation;
Console.WriteLine("Enter next donation amount, or " +
QUIT + " to quit ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
}
}
code 2
using System;
namespace donate
{
class donate
{
public static void Main()
{
begin:
string group;
int myint;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
goto begin;
default:
Console.WriteLine("Incorrect grade number.", myint);
goto begin;
}
}
}
}
So basically I want to find the total for each group using the 2nd code.
Any help would be greatly appreciated.
Don't use goto like that. Just use another while loop like you did in the first code segement.
It would be much more concise to say:
if (myInt > 3 && myInt < 7) { ... }
instead of using that switch statement.
Basically your code for summing up the donation amount does the trick, so just stick that inside a similar loop that handles what the group number is. If you do this you're going to want to use a different input to signify the end of donations vs the end of input altogether. It would be confusing if the application said "Enter 0 to quit input", followed by "Enter 0 to quit donation input".
You are very close with Code 2. If you put Code 2 inside while loop it works!
The only code I have written for you here is declared myint outside the while loop and initialised it to a non-zero value.
double total = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
total += donation;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Your total is {0}", total.ToString("C"));

Categories