When entering zero the while loop gives the wrong consolewriteline - c#

i have made a while loop to check if the input year is a leap year or not. This works perfectly, but when entering a '0' I always get the "0 is a leap year.". The purpose of 0 is to stop the while loop. It shouldnt print anything.
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = 0;
bool numberIsZero = false;
while (!numberIsZero)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input == 0)
{
numberIsZero = true;
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
else if (input > 0 && input % LeapYear == 0 || input % Year == 0) // input groter dan 0 EN result moet na berekening van 4 op 0 komen OF berekening delen door 400 op 0.
{
Console.WriteLine($"{input} is a leap year.");
}
else
{
Console.WriteLine($"{input} is not a leap year.");
}
}

The/a while loop will not magically stop because its condition has changed. The condition is only checked once every iteration before the loop's body is entered.
You have two options: if/else to only conditionally execute the second part of the loop's body or break to abort the loop early.
Option 1:
while (!numberIsZero)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input == 0)
{
numberIsZero = true;
}
else // <-- else here
{
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
else if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
else
{
Console.WriteLine($"{input} is not a leap year.");
}
}
}
}
Option 2:
while (!numberIsZero)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input == 0)
{
numberIsZero = true;
break; // <-- terminates loop
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
else if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
else
{
Console.WriteLine($"{input} is not a leap year.");
}
}

Related

Why does my 'averageScore' come out as 0?

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

C#: throwing exception Value cannot be null for list<int>

Test function returning null when user input is 10. please guide me how to handle this situation
List<int?> test10 = testInt(9, 10).ToList();
public static List<int?> testInt(int pagetotal, int userinput)
{
List<int?> _data = null;
if (userinput <= 10 && userinput != 0)
{
if (userinput <= pagetotal)
{
_data = Enumerable.Repeat(pagetotal / userinput, userinput - 1).ToList();
int y = (pagetotal - pagetotal / userinput * (userinput - 1));
_data.Add(y);
}
}
return _data;
}
_data is set to a non-null value only when all these conditions are true:
userinput <= 10 - this is true, because userinput is 10
userinput != 0 - this is true, because userinput is 10
userinput <= pagetotal - this is false, because userinput is 10 while pagetotal is 9
You need to decide what to return when pagetotal is less than userinput. Currently it is null, but you could potentially return an empty list:
if (userinput <= pagetotal) {
...
} else {
_data = ...
}
userinput <= pagetotal
That part prevents _data from being initialized if userinput >=10 (with pageTotal=9).
I think it is better to normalize userinput first.
You can add following line:
if(userInput > total)
userInput = total;
if(userInput <1)
userInput =1;

Break loops using while statement

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

Using exception handling if input is integer and between 0-9 in c#

This is my code so far to check if input is integer. I also want to check if integer is between 0-9. How do I do that?
int selectionInput = 0;
bool validInput = false;
while (validInput == false)
{
try
{
Console.Write("{0,30}", "Make a Selection >> ");
selectionInput = int.Parse(Console.ReadLine());
validInput = true;
}
catch
{
Console.WriteLine("Invalid Choice - please select from 0 - 9");
}
}
console.readline();
selectionInput = int.Parse(Console.ReadLine());
If(selectionInput >= 0 && selectionInput <= 9)
validInput = true;
else
validInput = false;
or
selectionInput = int.Parse(Console.ReadLine());
validInput = (selectionInput >= 0 && selectionInput <= 9)
To put what zzxyz suggests in the comments (using int.TryParse()):
int selectionInput = 0;
bool validInput = false;
while (validInput == false)
{
try
{
Console.Write("{0,30}", "Make a Selection >> ");
validInput = int.TryParse(Console.ReadLine(), out selectionInput);
if (validInput && (selectionInput < 0 || selectionInput > 9))
validInput = false;
}
catch
{
Console.WriteLine("Invalid Choice - please select from 0 - 9");
}
}
The if statement checks first if the input is a valid integer (see int.TryParse()) and then if its a valid integer and not in the range 0 to 9, it sets validInput to false.
If its not a valid integer in the first place, validInput is already false, and the if statement won't matter.
Here is my suggestion:
int selectionInput = 0;
do
{
Console.Write("{0,30}", "Make a Selection >> ");
Int32.TryParse(Console.ReadLine(), out selectionInput);
if (selectionInput > 10 || selectionInput < 1)
Console.WriteLine("Please input numbers between 1 to 10");
} while (selectionInput > 10 || selectionInput < 1);
Console.ReadLine();
Basically you do try catch statement when you are catching an error and not making a condition that if that condition fails, you do catch in on error block.
Usually try-catch error are good for error logs or you are really expecting an error on your code. Error is different from if-else condition/flow control.

repeat a if else statement

How do I make it after the if statement comes true it will not execute and I can re-enter another set of numbers?... to stop it though i will have it to enter -1 to exit.
static void Main(string[] args)
{
{
// first enter 2016, then 2000, then 2015 and get multiple results
int Year;
Console.WriteLine("Please enter a year: ");
Year = Convert.ToInt32(Console.ReadLine());
if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
{
Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
{
Console.WriteLine("the 2000 works", Year);
}
if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
{
Console.WriteLine("2015 works", Year);
}
else
{
// startover
}
Console.ReadLine();
}
}
It is bit unclear, since you want to recur the process until you press -1, you could do something like this .
int Year;
do
{
Console.WriteLine("Please enter a year: ");
if(!int.TryParse(Console.ReadLine(), out Year))
{
Console.WriteLine("invalid input");
continue;
}
if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
{
Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
{
Console.WriteLine("the 2000 works", Year);
}
if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
{
Console.WriteLine("2015 works", Year);
}
} while(Year != -1);
//Console.ReadLine(); not required.
Working Code
If you are just testing to see if the year entered is a leap year, you could just use DateTime.IsLeapYear()
if(DateTime.IsLeapYear(Year))
{
Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
else
{
Console.WriteLine("The Year you have entered is NOT a Leap Year {0}.", Year);
}

Categories

Resources