Console (Input string was not in correct format) - c#

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
}

Related

Inputting values for jagged array

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] + " ");
}
}
}
}

How to count number of 1s without using an array?

static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
int[] a = new int[m];
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1s in the Entered Number : "+count);
Console.ReadLine();
}
here get each value into the array, and check each value equal to one are not. But i need this task without using an array. Could you please help us.
Just check the input when it's entered, without storing it:
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
if(Console.ReadLine() == "1")
count++;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();
}
You can simply keep a count where you add it to the array
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
count += Console.ReadLine() == "1" ? 1 : 0;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();
You could use LINQ and remove the for loop as well as the array.
Console.WriteLine("Enter the Limit : ");
int m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
int count =
Enumerable
.Range(0, m)
.Select(n => Console.ReadLine())
.Where(x => x == "1")
.Count();
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();
I would advice using more meaningful variable names and adding input validation Int32.TryParse instead Convert.ToInt32.
Just do the if (o == 1) check in the first for and forget about the second one.
You can use List instead of array.
code is here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberofOnes
{
public class Program
{
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
List<int> a = new List<int>();
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a.Add( Convert.ToInt32(Console.ReadLine()));
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();
}
}
}

How to add elements to an array based on a condition?

I'm working on this simple C# program adding elements to an array. I allow the user to enter 5 numbers, and if the user enters an INVALID valid I have a message for that. My issue is that whether the users enters an invalid number or not I still want to add 5 numbers to my array.
My code works, but let's say the user enters 3 numbers and then 2 words and I end up having ONLY 3 numbers, but I want the 5 numbers no matter what. What am I doing wrong?
Here's my code:
int[] numbers = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
You can reduced increment count by 1, when user inputs wrong/no number.
Also note, you are code currently reading input only for 4(not 5 as question description says.) numbers.
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
i--;
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
try using do-while
int[] numbers = new int[4];
int i = 0;
do
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
i++;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
} while (i < 5);
Console.WriteLine("\nYour entered numbers are\n");
for (int j = 0; j < numbers.Length; j++ )
{
Console.Write(numbers[j] + " ");
}
You could use while loop here. See the below code
int[] numbers = new int[5];
int i = 0;
while (i < 5) {
Console.WriteLine ("Enter a number: ");
string c = Console.ReadLine ();
int value;
if (int.TryParse (c, out value)) {
numbers[i] = value;
i++;
} else {
Console.WriteLine ("You did not enter a number\n");
}
}
for (i = 0; i < numbers.Length; i++) {
Console.Write (numbers[i] + " ");
}
You can reduce the code using while loop. Also its better to change the last for loop to foreach
int[] numbers = new int[5];
int i = 0;
while (i < 5)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (!int.TryParse(c, out value)) continue;
numbers[i] = value;
i++;
}
foreach (int t in numbers)
Console.Write(t + " ");

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

Is there a way to enter number without showing them immediately?

I want to enter 10 numbers, and then show them in 1 line like this:
1,4,5,2,456,23,... and so on..
and it keeps writing them as I am entering them, and in the end when it's supposed to show all numbers in 1 line it shows only the last one.
I know it's possible with random numbers but when I enter them on my own I don't know how not to show them at all or keep them in 1 line and if it is even possible?
int a;
int x;
Console.WriteLine("a:");
a = int.Parse(Console.ReadLine());
x = 10;
for (int i = 0; i < x; i++)
{
a = int.Parse(Console.ReadLine());
}
Console.ReadKey();
you can use
Console.ReadKey(true)
it reads a key from console and does not show it.
you can use this to read word from console without showing it
public static string ReadHiddenFromConsole()
{
var word = new StringBuilder();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (word.Length > 0)
{
word.Remove(word.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
word.Append(i.KeyChar);
Console.Write("*");
}
}
return word.ToString();
}
You can use this code:
static void Main(string[] args)
{
int length = 10;
int[] myNumbers = new int[length];
for (int i = 0; i < length; i++)
{
Console.Write("Enter number:" );
myNumbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("Your numbers: {0}", string.Join(",", myNumbers));
}
i dont know how to write them at the end all in 1 line?
Well you need to save them as they are entered:
int num;
var nums = new List<int>();
while (nums.Count < 10)
{
Console.Write("Enter: ");
if (int.TryParse(Console.ReadLine(), out num))
{
nums.Add(num);
Console.Clear();
}
}
Console.WriteLine(string.Join(", ", nums));

Categories