I am writing a program that takes the scores of homework assignments, puts them in a array, then averages them. But I need to make it so that these grades range from 1-10. I am not sure how to make it only accept Numbers 1-10. Everything else is complete.
Here is what i have so far:
namespace AverageScore
{
class AverageScore
{
//prompt user to enter the size of the array
public int GetNum()
{
Console.WriteLine("Please enter how many scores you want to save!");
string strNum = Console.ReadLine();
int num = int.Parse(strNum);
return num;
}
static void Main(string[] args)
{
AverageScore scoreObject = new AverageScore();
int arraySize = scoreObject.GetNum();
//define a double array to save scores
double[] scoreArray = new double[arraySize];
string inValue = "";
double sum = 0,
intValue;
Console.WriteLine("Please enter all homework scores");
int counter = 0;
while (counter < arraySize)
{
inValue = Console.ReadLine();
while (double.TryParse(inValue, out intValue) == false)
{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Array.Sort(scoreArray);
double lowest= scoreArray[0];
double highest = scoreArray[arraySize-1];
sum = sum - lowest - highest;
double average = sum / arraySize;
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
Console.Read();
}
}
}
so your problem is to restrict a input to 1-10 correct?
Why not just:
public int InputGrade()
{
Console.Clear();
Console.WriteLine("Please enter a grade [1-10]");
var grade = -1;
if (!Int32.TryParse(Console.ReadLine(), out grade))
return InputGrade();
if (grade < 1 || grade > 10)
return InputGrade();
return grade;
}
then you should be able to use it like this and it is cleaner:
while (counter < arraySize)
{
var grade = InputGrade();
sum += grade;
scoreArray[counter++] = grade;
}
recommendation
Indeed you should refactor the input from the calculation part - you code will get much more cleaner and more readable:
IEnumberable<int> InputGrades()
{
var count = GetNum();
var grades = new List<int>();
for (var i = 0; i < count; i++)
grades.Add(InputGrade());
return grades;
}
void OutputScores(IEnumerable<int> grades)
{
var scores = grades.Cast<doulbe>().ToArray();
var lowest = scores.Min();
var highest = scores.Max();
var average = scores.Average();
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
}
Adjust the while loop condition to check that the number is in range (added a simple string format to present the previous invalid entry):
while (double.TryParse(inValue, out intValue) == false || intValue < 1.0 || intValue > 10.0**)
{
Console.WriteLine(String.Format("Invalid input = {0} stored in intValue", intValue));
inValue = Console.ReadLine();
}
This should do it:
while (counter < arraySize){
inValue = Console.ReadLine();
while (true){
if(double.TryParse(inValue ,out intValue) {
if(intValue >=1 && intValue <=10){
break;
}else{
Console.WriteLine("Input must be in the range 1-10");
inValue = Console.ReadLine();
}
}else{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Uses a loop to check if the value entered is correct:
while (int.Parse(inValue) < 1 || int.Parse(inValue) > 10) inValue = Console.ReadLine();
Related
Working on an assignment where i need to accomplish the following: On a survey a question asks the surveyed person to rate something from 1-5 (whole number). The end user of your program iinputs the answers for that question on an unknown number of surveys. Write a program that allows this and outputs the percent response for each value (1, 2, 3, 4, and 5).
I did a previous Console app with a loop to collect an average and I am unsure how to collect a percent response on 5 different possible inputs.
Below is my previous code.
namespace WhileLoopsMean
public class MeanProgram
static void Main(string[] args)
{
long test, sum, loop, count;
double avg;
Console.Write("How many tests? ");
count = long.Parse(Console.ReadLine());
sum = 0;
loop = 1;
while (loop <= count)
{
Console.Write("enter score " + loop + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
loop = loop + 1;
}
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.WriteLine("\n\nenter a score of -100 to end\n");
count = 1;
sum = 0;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
while (test != -100)
{
count = count + 1;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
if (test != -100)
{
sum = sum + test;
}
else { }
}
count = count - 1;
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.ReadKey();
class Program {
static void Main(string[] args) {
string input = "";
List<List<int>> answers = new List<List<int>>();
int questionsCount = ReadInt32("The number of questions: ");
for (int i = 0; i < questionsCount; i++) {
answers.Add(new List<int>());
}
while (input == "" || input == "y") {
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
a.Add(ReadInt32($"Question [{i}]: "));
}
input = Read("Continue (y/n)? ").ToLower();
}
WriteLine("End of input!");
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
Write($"Average for question[{i}]: {a.Average()}\n");
}
ReadKey();
}
static string Read (string a) {
Write(a);
return ReadLine();
}
static int ReadInt32 (string a = "") {
Write(a);
return ToInt32(ReadLine());
}
}
Try this out. You can customize the questions. And note that to use Write() and WriteLine(), you should add
using static System.Console;
at the top, in the references of the project.
Ok, I'm attempting to make a simple program that reads in number of pizzas sold for a given day and then have the user input the type of pizza sold for that day (with this I need to use the Split() with the user input).
I'm having issues populating the columns for my jagged array.
Now, I can get what I have to work for only 1 pizza sold, but anything beyond that it is not taking in my user input for the type of pizzas sold for that day (the column values). It's not reading in the user input as separate items so once I input, it goes to the next line like it's waiting for data instead of moving on. (Since I'm testing this for one day, it would end the program once the user input was read in).
I'm not quite sure where my issue is with my loops putting in my column values, but I'm figuring it has something with reading in the user input and placing that in the column of the jagged array. Any help would be great.
static void Main(string[] args)
{
Greeting();
string[][] pizza = new string[7][];
GetPizzas(pizza);
}
static void Greeting()
{
Write("Welcome to Z's Pizza Report!");
}
static void GetPizzas(string[][] array)
{
int numOfPizza;
string day;
for (int r = 0; r < array.Length; r++)
{
if (r == 0)
{
day = "Monday";
Write("How many total pizzas were there for {0}? ", day);
numOfPizza = int.Parse(ReadLine());
while (numOfPizza < 0)
{
Write("Number cannot be negative. Try Again: ");
numOfPizza = int.Parse(ReadLine());
}
array[r] = new string[numOfPizza];
Write("Enter all the pizzas for {0}, seperated by spaces: ", day);
for (int c = 0; c < array[r].Length; c++)
{
string total = ReadLine();
array[c] = total.Split(' ');
while (array[r] != array[c])
{
Write("Input does not match number needed. Try Again: ");
total = ReadLine();
array[c] = total.Split(' ');
}
}
}
else if (r == 1)
{
day = "Tuesday";
}
else if (r == 2)
{
day = "Wednesday";
}
else if (r == 3)
{
day = "Thursday";
}
else if (r == 4)
{
day = "Friday";
}
else if (r == 5)
{
day = "Saturday";
}
else
{
day = "Sunday";
}
}
}
The code seems overly complicated to me, but does something like this help? Oh, notice that I'm using the built-in DayOfWeek enum to parse the friendly name for the day. The difference between this and yours is that Sunday is day 0.
This line of code casts the integer to the enum, and then gets the string value:
var dayOfWeek = ((DayOfWeek)i).ToString();
I also added a helper function to get an integer from the user. It takes in a prompt string, an error string, an optional min value and an optional max value, then it prompts the user for an integer and won't return until they enter a valid value:
static int GetIntFromUser(string prompt, string error,
int minValue = int.MinValue, int maxValue = int.MaxValue)
{
int result;
if (!string.IsNullOrEmpty(prompt)) Console.Write(prompt);
while (!int.TryParse(Console.ReadLine(), out result)
|| result < minValue || result > maxValue)
{
if (!string.IsNullOrEmpty(error)) Console.Write(error);
}
return result;
}
The rest of the code looks like:
static void Main(string[] args)
{
var pizzasSold = new string[7][];
GetPizzas(pizzasSold);
for (int i = 0; i < pizzasSold.Length; i++)
{
var dayOfWeek = ((DayOfWeek)i).ToString();
Console.WriteLine("You sold {0} pizzas on {1}: {2}",
pizzasSold[i].Length, dayOfWeek, string.Join(", ", pizzasSold[i]));
}
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
static void GetPizzas(string[][] array)
{
for (int r = 0; r < array.Length; r++)
{
var dayOfWeek = ((DayOfWeek)r).ToString();
var numPizzasSold =
GetIntFromUser($"How many total pizzas were there for {dayOfWeek}? ",
"Number cannot be negative. Try Again: ", 0);
Console.Write($"Enter all the pizzas for {dayOfWeek}, seperated by spaces: ");
var pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
while (pizzasSold.Length != numPizzasSold)
{
Console.Write($"Input does not match number needed. Try Again: ");
pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
}
array[r] = pizzasSold;
}
}
using System;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
int[][] n = new int[3][];
int i;
n[0] = new int[4];
n[1] = new int[3];
n[2] = new int[2];
// n[1] = new int[] { 1, 2, 3 };
// Console.WriteLine("enter the rollno");
for (i = 0; i < 4; i++)
{
n[0][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 3; i++)
{
n[1][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 2; i++)
{
n[2][i] = Convert.ToInt32(Console.ReadLine());
}
// for (i = 0; i < 3; i++)
// {
// n[i][j] = Convert.ToInt32(Console.ReadLine());
//}
for (i = 0; i <4; i++)
{
Console.Write(n[0][i] + " ");
}
Console.WriteLine();
for (i = 0; i < 3; i++)
{
Console.Write(n[1][i] + " ");
}
}
}
}
I am trying to write a program using a loop with a decrement and not to be able to use the same number twice. If using the same number, I would want a "invalid number" displayed. It is a number system set up to read numbers between 10 and 100. If it goes over 100, "invalid number" is displayed. This is what I have so far:
string userNumber;
int userNumberInt;
int previousNumber = 0;
for (int counter = 0; counter <= 10; counter++)
{
Console.WriteLine("Enter your number");
userNumber = Console.ReadLine();
userNumberInt = Convert.ToInt32(userNumber);
if ((userNumberInt <= 100) && (userNumberInt >= 10))
{
Console.WriteLine("Your number is " + userNumber);
previousNumber = userNumberInt;
}
else if
(previousNumber == userNumberInt)
{
Console.WriteLine("Number is invalid.");
}
// number is invalid
else
// number is valid
{
Console.WriteLine("Invalid number.");
counter--;
}
}
Console.ReadLine(); // for last enter key
}
}
}
With your use of previous, the same numbers could be entered. For example, the first number entered could be 12, so 12 becomes previousNumber. Then when you enter 12 again you'll display "invalid number" which is good, but you enter 13, then 13 becomes the previousNumber and now you can enter 12 again. So what you should do is store all of your valid numbers in a list and check if your userInput is in the list so that you're not using duplicate numbers.
public static void Main(string[] args)
{
List<int> validInputs = new List<int>();
for (int counter = 0; counter <= 10; counter++)
{
Console.Write("Enter a number: ");
string stringInput = Console.ReadLine();
int numberInput;
if (int.TryParse(stringInput, out numberInput))
{
if ((10 <= numberInput && numberInput <= 100) &&
validInputs.Contains(numberInput) == false)
{
Console.WriteLine("Number is valid");
validInputs.Add(numberInput);
}
else
{
// This is not a valid number cause it's not in the range or it's a duplicate
Console.WriteLine("Invalid number");
counter--;
}
}
else
{
// This is not a valid number
Console.WriteLine("Invalid number");
counter--;
}
}
}
Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}
This is what I have so far:
namespace factorials
{
class Program
{
static void Main(string[] args)
{
int number;
do
{
Console.WriteLine("What non-negative integer do you want to factorial?");
while (!int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Please enter a whole number only");
calculate(ref number);
} while (number >= 0);
Console.WriteLine("Please enter a non-negative number");
}
static void calculate(ref int number)
{
int factorial;
int counter;
for (counter = number; counter <= number; counter++)
{
factorial = number * number;
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
}
}
}
}
Right now it just gives me the square of the numbers, not the factorial of them. How do I make it repeat the number of times as the input so it results in a factorial?
Also I am not sure if it's necessary to limit the program to non-negative integers only but if I want to that part is just ending the program right there instead of looping back to the beginning.
The for loop doesn't make any sense at all! If you are looking for a factorial, then you have to multiply all the numbers from one to the given number. That would be:
int factorial = 1;
for (counter = 1; counter <= number; counter++)
{
factorial = factorial * counter;
}
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
This would calculate the factorial of one number. You would have to repeat it for all the numbers you wanted.
Your loop assigns the square of the number to the result in a loop, and exits right away. You need to change it so that the result is repeatedly multiplied by numbers from 1 to N, inclusive.
Assign 1 to factorial, and multiply it by counter inthe loop:
factorial *= counter;
Don't forget to start your counter at 1.
I will give you hint.
Have a variable initialized to 1. Let's say it as Answer.
Run a loop from 1 to Number doing the operation of Answer = Answer * loopIterationVariable. After each iteration, increment loop iteration variable by 1.
static void Main(string[] args)
{
Console.WriteLine("Enter an integer number to factorise");
int ans = 1;
int a = int.Parse(Console.ReadLine());
for (int i = 1; i <= a; i++)
{
ans = ans * i;
}
Console.WriteLine(ans.ToString());
Console.ReadLine();
}
string str = Interaction.InputBox("Enter the number to find the factorial of: ");
double counter = double.Parse(str);
long factorial = 1;
while (counter > 1)
{
factorial *= (long)counter--;//factorial = factorial * counter - 1
}
MessageBox.Show("The factorial of " + str + " is " + String.Format("{0:N}", factorial));
I used a Microsoft.VisualBasic reference for Interaction.InputBox() method
Recursive Implementation as well as basic implementation is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}
int userinputF;
int counter;
int answer =1;
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}