Ii am new to c# and trying to create a validation through use of a while loop with the range from 0 - 5, my problem is that when this range is used it also accepts string characters, how can I stop this and only allow integers 0 - 5?
my code so far
static void Main()
{
int Rateing1, Rateing2;
Console.Write("Please rate from 0 - 5: ");
Rateing1 = valid_rating();
Console.Write("\nPlease rate from 0 - 5: ");
Rateing2 = valid_rating();
Console.WriteLine("\nRateing1 is {0}", Rateing1);
Console.WriteLine("Rateing2 is {0}", Rateing2);
}
static int valid_rating()
{
int rating;
int.TryParse(Console.ReadLine(), out rating);
while (rating < 0 || rating > 5)
{
Console.Write("\nInvalid Input, please input an integer from 0 - 5");
Console.Write("\nPlease enter new rating: ");
int.TryParse(Console.ReadLine(), out rating);
}
return rating;
}
Change your loop to this:
while (!int.TryParse(Console.ReadLine(), out rating) || rating < 0 || rating > 5)
{
Console.WriteLine();
Console.WriteLine("Invalid Input, please input an integer from 0 - 5");
Console.Write("Please enter new rating: ");
}
That is, you want the user to enter input again if any of the following is true:
They entered an invalid number.
The number they entered is less than 0.
The number they entered is greater than 5.
Your problem was that you were not using the value returned by int.TryParse (which is a bool indicating success or failure); you were simply using the value written to rating which, in the case of failure, is 0 (and !(0 < 0)).
Related
I need some help with the for-loop. I'm trying to sum up every fifth number that I type in, instead it sums them all up. What do I have to change?
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
for (count = 0; count <= 0; count += 5)
{
total = total + input;
}
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Assuming that you enter a list of numbers, and the 1st number and every five afterwards is added (so 1st, 6th, 11th, etc.):
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
if (count % 5 == 1)
total = total + input;
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
This works by using the modulo operator (%). The modulo operator returns the remainder of a division operation involving the number you specify.
In the code if (count % 5 == 1), the question is:
Is the remainder of count divided by 5 equal to 1?
If so, it adds the number. If not, it is skipped
The reason the remainder is one is because we want results 1, 6, 11, etc:
1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1
If you change the modulo value to 0 it will return the results at position 5, 10, 15, etc.
You could just store the numbers in a list and calculate it at the end:
var numbers = new List<int>();
Console.Write("Enter your number: ");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
numbers.Add(input);
input = int.Parse(Console.ReadLine());
}
var total = numbers.Where((x, i) => (i + 1) % 5 == 0).Sum(); // i + 1 since indexes are 0-based.
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
You can try this:
double total = 0;
int passover = 4;
int input = 0;
do
{
passover++;
Console.Write("Enter your number: ");
int.TryParse(Console.ReadLine(), out input);
if ( passover != 5 ) continue;
passover = 1;
total = total + input;
}
while ( input != 0 );
Console.WriteLine("The sum of every fifth numbers is: {0}", total);
Console.ReadKey();
I think the best way is to recover all the values before making the sum, this code works:
double total = 0;
int input = -1;
List<int> allInput = new List<int>();
while (input != 0)
{
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
allInput.Add(input);
}
for (int i = 0; i < allInput.Count()-1; i += 5)
{
total = total + allInput[i];
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Your sample would go forever, because there is no break point in your loop. You should always put a break point in your loop, otherwise it'll loop indefinitely.
Here is what you need :
int total = 0;
int count = 0;
Console.Write("Enter your number: ");
while (true)
{
int input = 0;
bool isNumber = int.TryParse(Console.ReadLine(), out input);
if (isNumber)
{
count++;
if (count % 5 == 0)
total += input;
}
else
{
break;
}
Console.Write("Add another number or press enter to get the sum : ");
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
So, you'll need first to put the user input inside a loop, and keep asking the user for adding another number until hits the condition where you close this loop. In the example, I decided to break the loop if the user typed anything not a number. but I told the user to press enter to get the some, to end the loop. For you, you'll need to translate that to your application breakpoint, how would you want the user to get the sum ?. Then, change the condition to your logic, so it breaks the loop and gets the sum.
another point is that int.TryParse. When you want to convert strings to numbers (int, long, decimal ..etc). You should always use `TryParse, this will verify the number, if the conversion failed, it'll return false. This way you can maintain the conversion and do something about it.
so I am trying to create a C# program that asks for a value between 1 and 100 that uses a loop to determine the sum of all values between 1 and the entered value and if the number entered in is less than one or more than 100 it prints out "Sorry. Try again." I've been working on this for days but I can't get it to print the sum, I keep getting 0 and whenever I test it and enter a number under one or over 100, it won't print the error message I want. Here is the code:
using System;
namespace PrintSumL
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
Random rand = new Random();
rand.Next(1, 51);
while (0 < s && s < 101)
{
sum += s;
s++;
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
{
}
{
}
}
}
}
}
You can think of the program as executing line by line from top to bottom, and only moving back up when it reaches the end of the while loop. The end of the while loop is the } that matches the { at the start of the loop.
Knowing that, you can see why it always says sum is zero. From your code:
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Since the program executes "line by line from top to bottom", it will first set sum to 0, and then print sum out. So it will always print "Sum of values: 0". If you want it to print out the sum after it has calculated it, then you need to move the WriteLine down below where the sum is calculated.
The same issue applies to the "Invalid input. Try again.": the line that prints this statement appears after while (0 < s && s < 101), so will only execute if s is between 0 and 101. Since you're trying to catch the scenario where s is not between 0 and 101, you'll need to move the statement to above the while loop.
So, to fix your immediate problems, just do two things:
1) move the two lines
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
to after the while loop (just after the } which is at the same level of indentation as while).
2) move the three lines
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
up to just below int s = Convert.ToInt32(Console.ReadLine());, and then double check the logic. It sounds like you want to print the statement if s is less than zero or s is greater than 101.
if loops are a requirement you should follow Heath Raftery instruction
else you could write something like:
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
if (s < 0 || s > 100)
Console.WriteLine("Invalid input. Try again.");
else
Console.WriteLine($"Sum of values: {Enumerable.Range(1,s).Sum()}");
}
or as haldo commented you could just use the formula of N * (N+1) / 2 and replace the last WriteLine with:
Console.WriteLine($"Sum of values: {s * (s+1) / 2}")
Try this:
static void Main(string[] args)
{
while (true)
{
Console.Write("Enter a number between 1 and 100: ");
int Number = Convert.ToInt32(Console.ReadLine());
if (Number < 0 || Number > 100)
Console.WriteLine("Sorry. Try again.");
else
{
int sum = 0;
for (int i = 1; i <= Number; i++)
{
sum = sum + i;
}
Console.WriteLine("Sum of values: " + sum);
}
}
}
Here is an algorithm that works...
Console.WriteLine("Enter a value between 1 and 100");
var input = int.Parse(Console.ReadLine());
int sum = 0;
if (input<1 || input>100) {
Console.WriteLine("Sorry, Try again");
}
else{
while(input > 2){
input-=1;
sum+=input;
}
}
Console.WriteLine("Sum of values: " + sum);
I'm trying to create a 5,4 array in C# where each cell is made up of user data. The code I have below works sometimes, but not consistently. I can input data into cell [4,5] or [3,4] for example. However, sometimes when I run the code It does not accept the data and displays an empty cell. and Any tips?
decimal[,] departments = new decimal[4, 5];
//int count = 0;
Console.WriteLine("If you would like to run the program, type enter");
string exit = Console.ReadLine();
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
Console.WriteLine("Enter sales");
departments[departmentNo, input] = decimal.Parse(Console.ReadLine());
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
Example output
0 0 0 0
0 0 0 0
0 0 500 0
500 0 0 0
You can use .GetUpperBound(dimension) to obtain the maximum bound (in the example below, it will return 1 for each dimension) for a specific dimension. Once you've got that, you just need to go through each position (I'm assuming you just need to fill data at each position).
Here's a sample:
int[,] items = new int[2, 2];
int width = items.GetUpperBound(0) + 1;
int height = items.GetUpperBound(1) + 1;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
string input;
int inputValue;
do
{
Console.WriteLine($"Please input value for ({x},{y}): ");
}
while (!int.TryParse(input = Console.ReadLine(), out inputValue));
items[x, y] = inputValue;
}
}
Or if you do need the user to be able to specify where the sales value goes, you can update your code to add some validation checks:
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
if (departmentNo > departments.GetUpperBound(0) || departmentNo < 0)
{
Console.WriteLine("Please enter a valid department number.");
continue;
}
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
if (input > departments.GetUpperBound(1) || input < 0)
{
Console.WriteLine("Please enter a valid input.");
continue;
}
Console.WriteLine("Enter sales");
if (!decimal.TryParse(Console.ReadLine(), out decimal value))
{
Console.WriteLine("Please enter a valid sales figure.");
continue;
}
departments[departmentNo, input] = value;
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
You probably want to change it to be similar to my example above so that you don't have to restart the entire loop again if the input is bad.
Because the departments has a fixed length of [4,5], it means the departmentNo can only be in range 0-3 and the input can only be in range 0-4. In addition, decimal keyword indicates a 128-bit data type, it's mean the value for a cell is in range ±1.0 x 10^28 to ±7.9228 x 10^28, which means 28-29 significant digits approximately. You should make some if conditions to make sure input values are in available range.
Here is my code. I want to have users enter any number of doubles continuously until 100 times (could be however number of times the user wants but less than 100). Display sum of all values entered. In my code, I don't know how to allow users to enter numbers continuously (im guessing you would have a while loop).
Thanks a lot!
Console.WriteLine("Enter double");
double.first = double.Parse(Console.ReadLine());
while(first != 0)
{
Console.WriteLine("Enter double");
int num = int.Parse(Console.ReadLine());
double sum;
while(num != 0)
{
double ten = num/10;
double tenth = Math.Floor(ten);
double oneth = num % 10;
sum = tenth + oneth;
Console.WriteLine("{0}", sum);
break;
}
first = double.Parse(Console.ReadLine());
}
I want to have users enter any number of doubles continuously until
100 times (could be however number of times the user wants but less
than 100).
You need to keep track of 3 things.
The next double.
The running total.
How many times the user has provided input.
Variables:
double next;
double runningTotal = 0;
int iterations = 0;
Now, to continuously receive input from the user, you can write a while-loop as you correctly identified. In this loop you should check for two things:
That the next value is a double and that it is not 0.
That the user has not provided input more than 100 times.
While-loop:
while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) {
// Count number of inputs.
iterations++;
// Add to the running total.
runningTotal += next;
}
Display sum of all values entered.
Simply write to the console.
Output:
Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal);
Complete example:
static void Main()
{
double runningTotal = 0;
double next;
var iterations = 0;
Console.Write("Enter double: ");
while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100)
{
runningTotal += next;
iterations++;
Console.Write("Enter double: ");
}
Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal);
Console.Read();
}
Edited after comment:
Ok, I'm still assuming this is homework, but here are the basics...
I would do this in two phases, data input, then calcualtion.
Create something to store the input in and a counter for the loop
var inputs = new List<double>();
var counter = 0;
Now comes you while loop for your inputs...
while(counter < 100)
{
var tempInput = 0.0D;
Double.TryParse(Console.ReadLine(), out tempInput);
if(tempInput == 0.0D)
{
// The user did not enter something that can be parsed into a double
// If you'd like to use that as the signal that the user is finished entering data,
// just do a break here to exit the loop early
break;
}
inputs.Add(tempInput);
// This is your limiter, once counter reaches 100 the loop will exit on its own
counter++;
}
Now you can just perform the calcualtions on the values you've accumulated...
var total = 0.0D;
foreach(var value in inputs)
{
total += value;
}
Now display the value in total.
Keep in mind there are a multitude of ways to do this this one is just an example to get you past the problem of aquiring the data.
I am trying to read in a string via input from the user and store it in an array. The string must be single digit numbers separated by a space. The user will enter exactly 20 numbers and no number can occur twice in a row.
Example string:
1 2 9 6 3 2 4 5 8 1 3 6 4 7 8 2 1 9 6 3
Here is the code I have to do this, as well as error check and it's not working properly. I think I am way over thinking the error checking. refString is an int array of size 20 in the code below.
case 2:
bool validated = false;
Console.WriteLine("\nPlease enter a 20 character reference string, each separated by a single space");
Console.WriteLine("A number should not occur twice in a row, ex: 1 5 4 4 6");
Console.WriteLine("Each character must be an integer 1-9");
Console.WriteLine("Example reference string: 1 2 3 4 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6");
Console.WriteLine("\nEnter reference string: ");
string s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); //split string and add numbers into array
int totalCount = refString.Length;
//if the user entered exactly 20 numbers, check to see if any of the numbers occur twice in a row
if (totalCount == 20)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
break;
}
}
}
while (totalCount != 20 || !validated)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
Console.WriteLine("\nError: reference string is NOT 20 numbers");
Console.WriteLine("\nEnter reference string: ");
s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
totalCount = refString.Length;
}
}
if (totalCount == 20)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
break;
}
}
}
}
break;
}
Try something like:
case 2:
bool correctNumber = true;
bool repeats = false;
Console.WriteLine("\nPlease enter a 20 character reference string, each seperated by a single space");
Console.WriteLine("A number should not occur twice in a row, ex: 1 5 4 4 6");
Console.WriteLine("Each character must be an integer 1-9");
Console.WriteLine("Example reference string: 1 2 3 4 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6");
Console.WriteLine("\nEnter reference string: ");
string s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); //split string and add numbers into array
correctNumber = refString.Length == 20;
if (correctNumber)
{
for (i = 1; i < 20; i++)
{
if(refString[i] == refString[i - 1])
{
repeats = true;
break;
}
}
}
else
{
Console.WriteLine("Error: reference string is NOT 20 numbers");
}
if (repeats)
{
Console.WriteLine("Error: reference string contains repeated numbers");
}
break;
That will check for the two fail conditions and output relevant messages.
You can use regex to check if there are two contiguous repeating digits
if(!Regex.IsMatch(n,#".*(\d) \1.*"))
s.Split(" ").Select(x=>int.Parse(x));
bool correct = false;
while(!correct){
// ask for numbers until correct
Console.WriteLine("\nEnter reference string: ");
string s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
int totalCount = refString.Length;
// check
if (totalCount == 20) {
correct = true;
for (i = 1; i < refString.Length; i++) {
if(refString[i] == refString[i - 1]) {
// consecutive number
Console.WrinteLine("Error: same consecutive number "+refString[i]);
correct = false;
break;
}
}
}else{
Console.WrinteLine("Error: not 20 elements");
}
}
One trick you can do is use Linq to filter out all the bad values, then check the count hasn't dropped below 20:
var listOfInts = stringTest.Split(' ').Select(n => Convert.ToInt32(n)).ToList();
// filter ints with adjacent values and out of range
var count =
listOfInts.Where((i, j) => (j + 1 == listOfInts.Count || // adjacent values
i != listOfInts[j + 1])
&& i > 0 && i < 10) // out of range
.Count(); // total
If count < 20, then you know something was invalid (either out-of-range or next to an identical value).