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");
}
}
}
}
}
Related
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);
}
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);
}
I have written a guess the number game between 1-100.
This is my code..
class Program
{
static void Main(string[] args)
{
while (true)
{
int randno = Newnum(1, 101);
int count = 1;
while (true)
{
Console.Write("Guess a number between 1 and 100, or press 0 to quit: ");
int input = Convert.ToInt32(Console.ReadLine());
if (input == 0)
return;
else if (input < randno)
{
Console.WriteLine("Unlucky, that number is too low - have another go!");
++count;
continue;
}
else if (input > randno)
{
Console.WriteLine("Unlucky, that number is too high - have another go!");
++count;
continue;
}
else
{
Console.WriteLine("Well done - you guessed it! The number was {0}.", randno);
Console.WriteLine("It took you {0} {1}.\n", count, count == 1 ? "attempt" : "attempts to guess it right");
break;
}
}
}
}
static int Newnum(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
How can I edit it so that if a user gets close to the number, say within 5 numbers, they are greeted with a message saying they're close?
You can use Math.Abs:
int diff = Math.Abs(input - randno);
if(diff <= 5)
{
// say him that he's close
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have to make it to when an integer entered that is not between 0 and 10 then it will display a message, whatever the number entered is not between 0 and 10. Also when -99 is entered it will exit the program. I have tried the while statement and nothing seems to be working.
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (int.TryParse(inValue, < 1 && > 10) == false)
WriteLine("Integer entered, {0}, is not between 0 and 10.");
if (int.TryParse(inValue, out score[i])
== false)
WriteLine("\n\tInvalid data - re-enter homework score: ");
}
You can't put the "greater than 10, less than 1" condition inside the TryParse() method, it does not support that. So check the condition separately. Also no need to check if (something == false) because that's identical to if (!something). I changed your ReadLine/Write/WriteLine's to have Console. prepended so it works on my system. You will need a while loop for the "please re-enter homework score" to work as you intend, but the code here does fix your original problem..
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
if (int.TryParse(inValue, out score[i]))
{
if (score[i] == 99)
{ Environment.Exit(0); }
bool between0and10 = score[i] <= 10 && score[i] >= 0;
if (!between0and10)
{ Console.WriteLine("Integer entered, {0}, is not between 0 and 10."); }
}
else
{ Console.WriteLine("\n\tInvalid data - re - enter homework score: "); }
}
Try this:
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (!int.TryParse(inValue, out score[i]))
{
WriteLine("\n\tInvalid data, StackOverflow did your homework! - re-enter homework score: ");
}
else if (score[i] < 1 || score[i] > 10)
{
WriteLine("Integer entered, {0}, is not between 0 and 10.");
}
}
int[] score = new int[8];
string sVal;
int val;
int i = 0;
while (i < score.Length)
{
Console.WriteLine("Please enter homework score [0 to 10] (-99 to exit):");
sVal = Console.ReadLine();
if (int.TryParse(sVal, out val))
{
//if quit
if (val == -99)
break;
//if valid range
if (val >= 0 && val <= 10)
{
score[i] = val;
i++;
}
else //invalid input range
Console.WriteLine("Invalid data - re-enter homework score:");
}
else //not a number
Console.WriteLine("Invalid data - re-enter homework score:");
}
int total = 0;
double avg;
int parsedScore;
//this bool will tell us if the data entered is valid
bool isValid;
int[] score = new int[8];
string inValue;
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
//here we check that the data entered is valid and set our bool to the result
isValid = int.TryParse(inValue, out parsedScore);
if (isValid && parsedScore == -99) //check first if it is -99 and then exit if need be.
{
System.Environment.Exit(0);
}
//if it is not valid we are going to prompt them to re-enter their number
if(!isValid || (parsedScore < 0 && parsedScore > 10))
{
Console.WriteLine("Integer not entered or {0}, is not between 0 and 10.", inValue);
i--; //we decrement i in order to let them re-enter at this index
}
else
{
//valid number, do logic here.
}
I have this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _121119_zionAVGfilter_Nave
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
}
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine(); }
}
}
The problem here is that if in the beginning I enter a negative or bigger than hundred number, I will get this message: "zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n".
If I then meenter -1, this what that shows up instead of the AVG: "Enter next zion, if you want to exit
tap -1 \n."
How can I solve this problem so when the number is negative or bigger than hundred and than tap -1 I will see the AVG an not another message?
You can just add a flag variable and it's done.
namespace _121119_zionAVGfilter
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
int flag = 0;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
if(zion== -1)
flag = 1;
}
cnt++;
sum = sum + zion;
if (flag == 1)
break;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0) { }
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine();
}
}
}
Just enclose this code that you don't want to be executed in if statement like this
if(zion != -1)
{
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0){}
}