C#. How to count digits entered from input? - c#

This is a code which multiplies numbers, user enters.
string x;
double t, s = 1;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();
It shows the result at the end, but how to make it show a total count of numbers entered?
For example: I enter 1, 2 and 3. So total count is 3.

string x;
double t, s = 1;
int count = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
count++;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count is: {0}", count);
Console.ReadLine();

It is good to use TryParse to avoid FormatException
Char.IsDigit returns true is current char is digit (obviously)
Example:
string x;
double t, s = 1;
int digitCount = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
if (!Double.TryParse(x, out t))
continue;
foreach (var c in x)
if (Char.IsDigit(c))
digitCount++;
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count of digits is: {0}", digitCount);
Console.ReadLine();

Why not a variable for counter?
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
int i=0;
while ((x = Console.ReadLine()) != "")
{
i++;
t = Convert.ToDouble(x);
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();

You have to count the loop iteration for that use a counter variable:
int loopCounter=0;
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
loopCounter++;
}
Console.WriteLine("The count is: {0}", loopCounter);

You could try counting the number of characters in the string input (x).
int temp=x.Length();

Related

While loop doesnt function when calculatin all positive numbers c#

I am making a while loop. The purpose of the loop is to take all the positive numbers and calculating the average. It works most of the time but not always. Can someone help? here is the code:
double count = 0;
int sum = 0;
int input = -1;
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
if (input < 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
}
}
if (input == 0)
{
Console.Write($"Average of all positive numbers is: { (sum += input) / count:0.00} ");
}
The second if is redundant it should work just like this
while (input != 0) {
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Your problem was when you enter a negative number it gives you the option to enter another, but then you enter a new iteration of the while loop and it asks you to enter another number. Removing the second if should fix your problem. Hope i helped :)
This code does not throw exceptions when non numeric data is entered
int count = 0;
long sum = 0;
int input;
Console.Write("Enter a number: ");
while (int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter a number: ");
if (input > 0)
{
sum += input;
count++;
}
}
Console.Write($"Average of all positive numbers is: {sum} / {Math.Max(count,1.0)} = {Math.Round( sum / Math.Max(count,1.0), 2)}.");

Error in parsing an input string to int value in c#

First if works great
Second if throws an exception
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray;
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0);
}
if (numbersArray[i] > numbersArray[i - 1])
{
if (numInput == "") {
break;
}
}
}
i++;
}
Console.WriteLine("You entered this series: ");
for (int j = 0; j < numbersArray.Length; j++)
{
Console.WriteLine(" " + numbersArray[j]);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
}
}
You can't parse a string wihout digits like numInput = ""
EDIT: Try this code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray = new []{1};
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
if (numInput == null || !numInput.All(char.IsDigit)) continue;
if (numInput != "")
{
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0); // <-- Code is unreachable!
}
}
i++;
}
else if(i >= 1)
{
break;
}
}
Console.WriteLine("You entered this series: ");
foreach (int t in numbersArray)
{
Console.WriteLine(" " + t);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
Console.ReadLine();
}
I assume you are trying to look at a index not existing.
Not sure of your language but I guess numbersArray[0] is the first index and numbersArray[1] is the second. So when you input your first number then you try to look at numbersArray[1] which doesn't exist.

C# Programming arrays

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();

Console (Input string was not in correct format)

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
}

while statement-to repeat it again

Everything is allright except the while statement.If you guys can help me that would be great.When the user write "Y" to do it again, he see: max value is: bla bla.
the user has to give a new positive number instead of to see the maximum value over and over again.
Console.WriteLine("Please give a positieve number. if you enter a negatieve number its not going to work");
int invoer = 0, max = 0;
string repeat = "";
do
{
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
Im guessing at what this is supposed to be doing....
{
//Console.WriteLine("Please give a positive number. if you enter a negative number its not going to work");
int invoer;
int max;
string repeat;
do
{
//they have given a negative number and wish to try again
Console.WriteLine("Please give a positive number.\nIf you enter a negative number its not going to work");
invoer = 0;
max = 0;
repeat = "";
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
}
I'm not 100% sure what you're trying to do, but it looks like you need to move your deceleration of invover and max into your do loop.

Categories