My try isn't catching my error messages,,, - c#

When I run my code I can enter any character and it gives me a letter grade back, which it isn't supposed to. What am I missing?
namespace ProjException
/* Include exception handling techniques with the traditional averaging program.
* Allow the user to input multiple sets of scores.
* Ensure that only numeric values are entered and that values fall between 0 and 100.
* Calculate the average for each set of values.
* Test the result to determine whether an A, B, C, D, or F should be recorded. The scoring rubric is as follows: A—90–100; B—80–89; C—70–79; D—60–69; F < 60.
* Your solution should include exception-handling techniques with a minimum of three appropriate catch clauses.
*/
{
class Program
{
static void Main(string[] args)
{
// Variables Declared
int grade = 0;
int total = 0;
int count = 0;
double average;
string letterGrade = "F";
while (grade != -99)
{
try
{
Console.Write("Enter a Grade 0-100 -99 to quit: ");
grade = int.Parse(Console.ReadLine());
if ((grade != -99 && grade < 0) || grade > 100)
throw new ArgumentOutOfRangeException();
if (grade != -99)
{
total += grade;
count++;
}
}
catch (FormatException e)
{
Console.WriteLine("Grade must be a number");
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Grade must be between 0 and 100 or -99 to quit");
}
catch (Exception e)
{
Console.WriteLine("Some other error occurred");
Console.WriteLine(e);
}
average = (double)total / count;
if (average >= 90)
letterGrade = "A";
else if (average >= 80)
letterGrade = "B";
else if (average >= 70)
letterGrade = "C";
else if (average >= 60)
letterGrade = "D";
else
letterGrade = "F";
Console.WriteLine("Your letter grade is " + letterGrade);
Console.ReadKey();
}
}
}
}

You don't change the flow, when you catch an exception (which works fine). The program will continue after your try catch-blocks and eventually reach the output of the grade. One way here is to use continue in the catch blocks, to cause the loop to end the current iteration and start the next from the beginning.

Related

Why does my 'averageScore' come out as 0?

why does my code not calculate an average score when entering "-1" into the console? It comes up at 0. It's a part of a loop exercise, so I'm sure there are faster ways to code this. I want to fix it within my current C# comprehension.
Here's the task
using System;
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
if(int.TryParse(individualScore, out individualScoreIntoInt) && individualScoreIntoInt > 0 && individualScoreIntoInt < 21)
{
totalScore += individualScoreIntoInt;
//longer way: totalScore = individualScoreIntoInt + totalScore;
}
else if(individualScoreIntoInt < 0 || individualScoreIntoInt < 20)
{
Console.WriteLine("Enter a score > 0 and < 21");
continue;
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
scoreCount++; // adding the individualscore entered to the count. writing it here so that it's only
//added to the count if it meets the requirements
}
}
}
}
Order of operations was incorrect:
1st validate if it's -1 or not,
2nd parse value and if it's possible perform below operations, if not drop error.
This was logic issue, rather than code itself.
You had added iteration despite exceptions, you didn't include possibility of 21 etc.
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
}
else if (int.TryParse(individualScore, out individualScoreIntoInt))
{
if(individualScoreIntoInt > 0 && individualScoreIntoInt <= 21)
{
totalScore += individualScoreIntoInt;
scoreCount++;
}
//as mentioned in comment else here would also work, it's unnecessary to add any other validation.
else if (individualScoreIntoInt < 0 || individualScoreIntoInt > 21)
{
Console.WriteLine("Enter a score > 0 and < 21");
}
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
}
}
}

Making a word into a sentinel value in C#

I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;

C# Sharp Grade program using for and while

I'm new at C# and am having trouble with nested loops. I'm working on a Grading program with a menu. The first menu asks the user how many grades would they like to enter. Then, the user enters the grades. The Second menu figures out the average and grade. I'm having trouble with a nested loop where it would ask you a given number of time to enter grades.
Once that is done, I'm also having trouble with how I would pass that info to the second menu to get the average. I done something like this better in Java, but there we had a set number of grades; then, we made a variable for each grade. Finally we summed them and divided by a set number.
bool exit = false;
do
{
Console.WriteLine("1. Enter Grades");
Console.WriteLine("2. Get Average");
Console.WriteLine("3. My program");
Console.WriteLine("4. exit");
string input = Console.ReadLine();
Console.WriteLine("");
if (input == "1")
{
int totalGrades = 0;
double grades;
double grade, finalGrade = 0;
//User Input
Console.WriteLine("How many grades do you want to enter? ");
//While loop for TryParse
while(!int.TryParse(Console.ReadLine(),out totalGrades))
{
Console.WriteLine("Please enter a valid number");
}
while (totalGrades < 1)
{
Console.WriteLine("Enter Grade: ");
string input = Console.ReadLine();
for (int i = 0; i<= totalGrades; totalGrades++)
Console.WriteLine(totalGrades);
}
Console.ReadLine();
}
else if (input == "2")
{
double average = 0;
if (average >= 90)
{
Console.WriteLine($"The average is a {average} which is an A.");
}
else if (average >= 80)
{
Console.WriteLine($"The average is a {average} which is an B.");
}
else if (average >= 70)
{
Console.WriteLine($"The average is a {average} which is an C.");
}
else if (average >= 60)
{
Console.WriteLine($"The average is a {average} which is an D.");
}
else
{
Console.WriteLine($"The average is a {average} which is an E.");
}
}
else
{
exit = true;
}
}
while (exit == false);
I've changed a few things in order to make the code easier to understand.
private static void Main(string[] args)
{
ProgramLoop();
}
private static void ProgramLoop()
{
var grades = new List<double>();
double average;
var exit = false;
do
{
System.Console.WriteLine("1. Enter Grades");
System.Console.WriteLine("2. Get Average");
System.Console.WriteLine("3. My program");
System.Console.WriteLine("4. exit");
var input = System.Console.ReadLine();
System.Console.WriteLine("");
switch (input)
{
case "1":
grades = EnterGrades();
break;
case "2":
average = GetAverage(grades);
break;
case "3":
MyProgram();
break;
case "4":
exit = true;
break;
default:
System.Console.WriteLine($"'{input}' is not a valid choice.");
break;
}
}
while (exit == false);
}
private static List<double> EnterGrades()
{
int numberOfGrades = 0;
var grades = new List<double>();
System.Console.WriteLine("How many grades do you want to enter? ");
// Read number of grades
while (!int.TryParse(System.Console.ReadLine(), out numberOfGrades) || numberOfGrades < 1)
{
System.Console.WriteLine("Please enter a valid number");
}
while (grades.Count != numberOfGrades)
{
// Read grade
System.Console.WriteLine("Enter Grade: ");
double grade;
while (!double.TryParse(System.Console.ReadLine(), out grade) || grade < 0 || grade > 100)
{
System.Console.WriteLine("Please enter a valid grade between 0.0 and 100.0");
}
grades.Add(grade);
}
return grades;
}
private static double GetAverage(IList<double> grades)
{
var average = grades.Average();
if (average >= 90)
{
System.Console.WriteLine($"The average is {average}, which is an A.");
}
else if (average >= 80)
{
System.Console.WriteLine($"The average is {average}, which is an B.");
}
else if (average >= 70)
{
System.Console.WriteLine($"The average is {average}, which is an C.");
}
else if (average >= 60)
{
System.Console.WriteLine($"The average is {average}, which is an D.");
}
else
{
System.Console.WriteLine($"The average is {average}, which is an E.");
}
return average;
}
I would recommend you to split your code into methods. The code will be easier to understand, and it's a great practice to not cram too much code together.
If you plan on adding more functionality and write more code, I would also recommend you to look into how you can apply object oriented programming to this, i.e. writing classes like a GradeCard.
So there are a couple things I'd like to highlight and I also added notes to the code. You want to keep 2 variables throughout your program/method to keep track of everything entered. They are the 2 pieces of average (1) Total and (2) Count of input numbers. See the code and read it line by line and see the comments. Hope this helps you. Feel free to ask questions if something doesn't make sense.
bool exit = false;
// added variables outside of loop so they are available everywhere in the method
double grades = 0;
int gradesCount = 0;
do
{
Console.WriteLine("1. Enter Grades");
Console.WriteLine("2. Get Average");
Console.WriteLine("3. exit");
string input = Console.ReadLine();
Console.WriteLine("");
if (input == "1")
{
int totalGrades = 0;
//User Input
Console.WriteLine("How many grades do you want to enter? ");
//While loop for TryParse
while (!int.TryParse(Console.ReadLine(), out totalGrades))
{
Console.WriteLine("Please enter a valid number");
}
// increment the count of grades by the number of grades the user wants to add
gradesCount += totalGrades;
// variable to keep a count and avoid infinite loop
int addedGradesCount = 0;
// while loop works like a for loop using our variable to keep count of grades we add
while (addedGradesCount < totalGrades)
{
Console.WriteLine("Enter Grade: ");
// variable to store entered grade
double newGrade = 0;
//Reusing code from while loop above for TryParse
while (!double.TryParse(Console.ReadLine(), out newGrade))
{
Console.WriteLine("Please enter a valid number");
}
// increment running total of grades with the user input number
grades += newGrade;
// output to user - got rid of loop through totalGrades
Console.WriteLine("You entered: " + newGrade + " - Total: " + grades);
// increment variable to keep count! if this is not here, you will have infinite loop
addedGradesCount++;
}
// Console.ReadLine(); // not needed
}
else if (input == "2")
{
// calculate average using the method variables we initialized at the beginning
double average = (grades / gradesCount);
if (average >= 90)
{
Console.WriteLine($"The average is a {average} which is an A.");
}
else if (average >= 80)
{
Console.WriteLine($"The average is a {average} which is an B.");
}
else if (average >= 70)
{
Console.WriteLine($"The average is a {average} which is an C.");
}
else if (average >= 60)
{
Console.WriteLine($"The average is a {average} which is an D.");
}
else
{
Console.WriteLine($"The average is a {average} which is an E.");
}
}
else
{
exit = true;
}
} while (exit == false);
Console.ReadKey();
this seems to work
static void Main(string[] args)
{
bool exit = false;
List<float> grades = new List<float>();
do
{
Console.WriteLine("1. Enter Grades");
Console.WriteLine("2. Get Average");
Console.WriteLine("3. My program");
Console.WriteLine("4. exit");
Console.WriteLine("");
string input = Console.ReadLine();
Console.WriteLine("");
if (input == "1")
{
int totalGrades = 0;
//User Input
Console.WriteLine("How many grades do you want to enter? ");
while (true)
{
try
{
totalGrades = Convert.ToInt32(Console.ReadLine());
break;
}
catch (FormatException)
{
Console.WriteLine("This is not a valid number");
continue;
}
}
Console.WriteLine("");
while (totalGrades > 0)
{
while (true)
{
try
{
grades.Add(Convert.ToInt32(Console.ReadLine()));
totalGrades--;
break;
}
catch (FormatException)
{
Console.WriteLine("This is not a valid number");
continue;
}
}
}
Console.WriteLine("");
}
else if (input == "2")
{
double average = grades.Average();
if (average >= 90)
{
Console.WriteLine($"The average is a {average} which is an A.");
}
else if (average >= 80)
{
Console.WriteLine($"The average is a {average} which is an B.");
}
else if (average >= 70)
{
Console.WriteLine($"The average is a {average} which is an C.");
}
else if (average >= 60)
{
Console.WriteLine($"The average is a {average} which is an D.");
}
else
{
Console.WriteLine($"The average is a {average} which is an E.");
}
Console.WriteLine("");
}
else if (input == "4")
{
exit = true;
} else
{
Console.WriteLine("This is not an option");
}
}
while (exit == false);
}

Break loops using while statement

I am writing a C# program that prints "true" if number <= 20 and "false" if number > 20 using a while loop but the program keeps on executing.
I want to break the program if it reaches certain number e.g. number > 26.
The code for the program is:
public static void Main()
{
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
while (numnber <= 20)
{
Console.WriteLine("True");
Console.ReadLine();
int number1 = numnber++;
while (numnber > 20)
{
Console.WriteLine("False");
Console.ReadLine();
}
}
}
you can just use break; Try this:
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
while (numnber <= 20)
{
Console.WriteLine("True");
Console.ReadLine();
int number1 = numnber++;
while (numnber > 20)
{
Console.WriteLine("False");
Console.ReadLine();
}
break;
}
But this programming is not good at all because you are breaking loop after all for this simply you can use if else like this..
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
if(numnber <= 20)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
According to your description, your major issue should be
the program keeps on executing
However, it's not going to reach 26 as #King King mentioned.
It stuck inside the inner while which should be replaced by if condition.
Lastly, if you have to exec the number check at least one time you can use do while
do
{
if (numnber <= 20)
{
Console.WriteLine("True");
}
else if (numnber > 20)
{
Console.WriteLine("False");
}
numnber++;
Console.WriteLine("number: {0}", numnber);
} while (numnber < 26);
Console.ReadLine();
Thank you all but the solution to the problem would be. The code is as follows:
public static void Main()
{
int number;
do
{
Console.WriteLine("Please enter a number");
number = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("True value. True value is supplied");
Console.ReadLine();
number++;
while (number >= 21 && number < 27)
{
Console.WriteLine("False value. False value is supplied");
Console.ReadLine();
number++;
}
} while (number <= 20);
} while (number > 27);
}

Catching an input error

I have this assignment for school where we have to use try and catch in order to ensure that the user doesn't input a negative number of donuts and data that is not an integer. I got the try/catch to work so that it asks for the number of donuts again when I enter a negative number, but when I enter a letter instead of a number for the number of donuts it comes up with the error message I created for it but doesn't give the option to enter the amount of donuts again. If someone could help me that would be greatly appreciated. Thanks. Here's what I got for my code:
using System;
public class CostofDonuts
{
public static void Main()
{
string lastName;
int number_Of_Donuts;
double Total_Cost, Final_Cost;
try
{
// Get user to input their last name
Console.Write("Enter customer's last name -> ");
lastName = Convert.ToString(Console.ReadLine());
//Get user to input amount of donuts purchased. Ensure that the integer inputted is positive.
do
{
Console.Write("Enter the amount of donuts purchased -> ");
number_Of_Donuts = Convert.ToInt32(Console.ReadLine());
if (number_Of_Donuts < 0)
Console.WriteLine("Invalid input, number of donuts must be positive");
} while (number_Of_Donuts <= 0);
//Calculate cost of donuts
if (number_Of_Donuts < 6)
Total_Cost = number_Of_Donuts * 0.5;
if (number_Of_Donuts <= 15)
Total_Cost = number_Of_Donuts * 0.4;
else
Total_Cost = number_Of_Donuts * 0.3;
//Calculate cost with tax
if (number_Of_Donuts < 12)
Final_Cost = (Total_Cost + 0.25) * 1.13;
else
Final_Cost = Total_Cost + 0.25;
// Output final results
Console.WriteLine("{0} bought {1} donuts which came to a total of {2:C}", lastName, number_Of_Donuts, Final_Cost);
Console.ReadLine();
}
catch (FormatException e)
{
Console.WriteLine("Input must be a positive integer");
}
catch (Exception e)
{
Console.WriteLine("Input must be a positive integer");
}
}
}
You need to use try / catch inside of your loop in order to keep continue:
do
{
Console.Write("Enter the amount of donuts purchased -> ");
try
{
number_Of_Donuts = Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Invalid input, number of donuts must be positive");
number_Of_Donuts = 0;
}
} while (number_Of_Donuts <= 0);
you can use int.TryParse
do
{
Console.Write("Enter the amount of donuts purchased -> ");
if(int.TryParse(Console.ReadLine(), out number_Of_Donuts ) && number_Of_Donuts >= 0)
break;
Console.WriteLine("Invalid input, number of donuts must be positive");
} while (number_Of_Donuts <= 0);
do
{
Console.Write("Enter the amount of donuts purchased -> ");
Int.TryParse(Console.ReadLine(), out number_Of_Donuts);
if (number_Of_Donuts < 0)
Console.WriteLine("Invalid input, number of donuts must be positive");
} while (number_Of_Donuts <= 0);

Categories

Resources