repeat a if else statement - c#

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

Related

When entering zero the while loop gives the wrong consolewriteline

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

How to properly use while loop with null int values for user input in C#

I am basically trying to continue a loop until user enters the required input. I got it to work if less than 1 or greater than 7 is input. But I still get an "Unhandled Exception" error if user inputs either space characters or just hits ENTER. Any help or suggestion is greatly appreciated.
Here is the code-
static void Main(string[] args)
{
string[] daysOfWeek = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
System.Console.WriteLine(" Which day would you like?");
System.Console.Write(" Choose from 1 and 7. ");
int? iDay = int.Parse(Console.ReadLine());
// Loops until user enters number from 1 - 7
while ( iDay < 1 || iDay > 7 || iDay is null )
{
if ( iDay > 0 && iDay < 8)
{
break;
}
System.Console.Write(" < INVALID - CHOOSE FROM 1 AND 7 > ");
iDay = int.Parse(Console.ReadLine());
}
string chosenDay = daysOfWeek[(int)iDay-1];
System.Console.WriteLine($"You chose {chosenDay}.");
Use int.TryParse
bool isValid = int.TryParse(Console.ReadLine(), out int iDay);
// Loops until user enters number from 1 - 7
while (!isValid || iDay < 1 || iDay > 7)
{
// This is redundant to the while clause
//if (iDay > 0 && iDay < 8)
//{
// break;
//}
System.Console.Write(" < INVALID - CHOOSE FROM 1 AND 7 > ");
isValid = int.TryParse(Console.ReadLine(), out iDay);
}

Not all code paths return a value - Enum practice

I've tried to execute a simple code just to study the enumeration topic.
Yet, I've faced this issue: "Not all code paths return a value".
Here is the code:
namespace ConsoleAppTest
{
class Program
{
enum Seasons { Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 || month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 || month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 || month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 || month <= 12)
{
return Seasons.Fall;
}
}
}
}
I wonder what could cause this problem.
Thanks :)
You should handle the else case. Your month integer could also be <1 or >12.
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 && month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 && month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 && month <= 12)
{
return Seasons.Fall;
}
else
{
throw new ArgumentOutOfRangeException("invalid month");
}
}
so if you call
WhichSeason(13); //throws exception
What should be returned if month, say -1 or 123? You can solve the problem in two main ways, silent:
// Please, notice "None"
enum Seasons { None, Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
return Seasons.Winter;
else if (month >= 4 && month <= 6)
return Seasons.Spring;
else if (month >= 7 && month <= 9)
return Seasons.Summer;
else if (month >= 10 && month <= 12)
return Seasons.Fall;
else
return Seasons.None;
}
Or throwing appropriate exception, ArgumentOutOfRangeException in the case
enum Seasons { Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
return Seasons.Winter;
else if (month >= 4 && month <= 6)
return Seasons.Spring;
else if (month >= 7 && month <= 9)
return Seasons.Summer;
else if (month >= 10 && month <= 12)
return Seasons.Fall;
else
throw new ArgumentOutOfRangeException(
"month",
"month must be in [1..12] range."); // Exception
}
Edit: I've preserved WhichSeason intact, but it seems that you have a logic error in the implementation and the right routine should be
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 2 || month == 12) // Jan, Feb and Dec
return Seasons.Winter;
else if (month >= 3 && month <= 5) // Mar-May
return Seasons.Spring;
else if (month >= 6 && month <= 8) // Jun-Aug
return Seasons.Summer;
else if (month >= 9 && month <= 11) // Sep-Nov
return Seasons.Fall;
else
return Seasons.None;
}
You should add && operator in your logic and should also handle if input doesn't match in your described conditions -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
class Program
{
enum Seasons { Winter, Spring, Summer, Fall,NotAValidInput };
public static void Main(string[] args)
{
Console.WriteLine(WhichSeason(-1));
}
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 && month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 && month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 && month <= 12)
{
return Seasons.Fall;
}
return Seasons.NotAValidInput;
}
}
}
Introduce a else block under else if . Method is not returning values in all cases and should be backed up with else .
with switch
static Seasons WhichSeason(int month)
{
switch (month)
{
case 1:
case 2:
case 3:
return Seasons.Spring;
case 4:
case 5:
case 6:
return Seasons.Summer;
case 7:
case 8:
case 9:
return Seasons.Fall;
case 10:
case 11:
case 12:
return Seasons.Winter;
default:
throw new Exception("The month is invalid!");
}
}

Calculating a leap year without the leap year function

I need to calculate if the current year at the runtime of the program is a leap year (divisible by 4, not divisible by 100 but divisible by 400) but without using the DateTime.LeapYear property. Can anyone suggest anything?
//DateTimePicker code
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTime now;
int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
now = DateTime.Now.Date;
if (now.Year / 4 == 0 && now.Year / 400 == 0)
{
months(1) = 29;
}
}
I think this covers the three criteria:
var year = now.Year;
if (year % 4 == 00 && !(year % 100 == 0 && year % 400 != 0))
{
....
}
Use the modulus operator % when checking divisibility. Also, when changing an array, use array indexers [], not parentheses:
if (now.Year % 4 == 0 && now.Year % 400 == 0)
{
months[1] = 29;
}

C# Console - Console.ReadLine returns wrong output

I have here a C# Console application, in which when I allow the user to input a certain number of records, the program will generate a quote number. This is for me to test the algorithm I formulated before I implement this in my program.
Example, when I input 23 (assuming this is the current record count in the database), the program will output "CQ-13-04-0023". But I got an output of "CQ-13-04-0051". My objective is when the series number in the given quote number reaches 9999, it will reset to 0001 when the number of records in the database reaches 10000 and above.
Here's my code:
class Program
{
static void Main(string[] args)
{
string QuoteRefNum = "";
string seriesCount = "";
DateTime year = DateTime.Now;
string strYear = year.ToString("yy");
string strMonth = year.ToString("MM");
Console.Write("Input the number of records: ");
int numberOfRecords = Convert.ToInt32(Console.Read());
numberOfRecords++;
if (numberOfRecords == 0)
{
seriesCount = "000" + numberOfRecords++;
}
else if (numberOfRecords >= 1 && numberOfRecords <= 9)
{
seriesCount = "000" + numberOfRecords;
}
else if (numberOfRecords >= 10 && numberOfRecords <= 99)
{
seriesCount = "00" + numberOfRecords;
}
else if (numberOfRecords >= 100 && numberOfRecords <= 999)
{
seriesCount = "0" + numberOfRecords;
}
else if (numberOfRecords >= 1000 && numberOfRecords <= 9999)
{
seriesCount = numberOfRecords.ToString();
}
else if (numberOfRecords >= 10000 && numberOfRecords <= 99999)
{
string newSetOfRecords = numberOfRecords.ToString();
int tempNumber = 0;
newSetOfRecords.Remove(0, 1);
tempNumber = Convert.ToInt32(newSetOfRecords);
if (tempNumber == 0)
{
seriesCount = "000" + tempNumber++;
}
else if (tempNumber >= 1 && tempNumber <= 9)
{
seriesCount = "000" + tempNumber;
}
else if (tempNumber >= 10 && tempNumber <= 99)
{
seriesCount = "00" + tempNumber;
}
else if (tempNumber >= 100 && tempNumber <= 999)
{
seriesCount = "0" + tempNumber;
}
else if (tempNumber >= 1000 && tempNumber <= 9999)
{
seriesCount = tempNumber.ToString();
}
}
QuoteRefNum = "CQ" + strYear + "-" + strMonth + "-" + seriesCount;
Console.WriteLine("The quote reference number is: " + QuoteRefNum);
}
}
This line is the problem:
int numberOfRecords = Convert.ToInt32(Console.Read());
It is returning the ASCII value.
Change it to:
int numberOfRecords;
Int32.TryParse(Console.ReadLine(), out numberOfRecords);
And remove numberOfRecords++
Explanation of what's going on:
The reason why you are getting 51 is because when you enter 23 number of records is set to 50 and then you increment the variable to 51 via numberOfRecords++
Problem is Console.Read(); when you type 23 end enter key Read() will return key value of first input character that is 2. ASCII Character value of 2 is 50
So you will get 51 after numberOfRecords++ as result
change Console.Read(); to Console.ReadLine(); and remove numberOfRecords++

Categories

Resources