using A = System.Console;
public void point()
{
int hour, minute;
A.Write("Enter Time (HH:MM) = ");
hour = A.Read();
A.Write(":");
minute = A.Read();
}
I want it to be like
"Enter Time (HH:MM) = 12(hour input):49(minute input)"
but it coming like
"Enter Time (HH:MM) = 12(hour input)
:49(minute input)
Simplest way (assuming you are reading from Console, and user will enter hour then press Enter, then enter minute and press Enter):
static void Main(string[] args)
{
int hour = 0, minute = 0;
const int MAX_NUMBER_OF_DIGITS = 2 ;
Console.Write("Enter Time (HH:MM) = ");
// store cursor position
int cursorLeft = Console.CursorLeft;
int cursorTop = Console.CursorTop;
// use ReadLine, else you will only get 1 character
// i.e. number more than 1 digits will not work
hour = int.Parse(Console.ReadLine());
Console.SetCursorPosition(cursorLeft + MAX_NUMBER_OF_DIGITS , cursorTop);
Console.Write(":");
minute = int.Parse(Console.ReadLine());
// Nitpickers! purposefully not using String.Format,
// or $, since want to keep it simple!
Console.Write("You entered: " + hour + ":" + minute);
}
Output:
Enter Time (HH:MM) = 17:55
You entered: 17:55
Though I would rather recommend you better and less error prone way like this (where user inputs HH:MM and presses Enter a single time i.e. enters a single string including : i.e. colon):
static void Main(string[] args)
{
int hour = 0, minute = 0;
Console.Write("Enter Time in format HH:MM = ");
string enteredNumber = Console.ReadLine();
string[] aryNumbers = enteredNumber.Split(':');
if (aryNumbers.Length != 2)
{
Console.Write("Invalid time entered!");
}
else
{
hour = int.Parse(aryNumbers[0]);
minute = int.Parse(aryNumbers[1]);
// Nitpickers! purposefully not using String.Format,
// or $, since want to keep it simple!
Console.Write("You entered: " + hour + ":" + minute);
}
}
Assuming that A is Console, you can do like this:
static void Main()
{
int hour, minute;
char[] hourChars = new char[2];
Console.Write("Enter Time (HH:MM) = ");
hourChars[0] = Console.ReadKey().KeyChar;
hourChars[1] = Console.ReadKey().KeyChar;
var hourString = new String(hourChars);
hour = int.Parse(hourString);
Console.Write(":");
minute = Console.Read();
}
Assuming A is the standard c# Console then you can use ReadKey instead of Read
ReadKey will read only one character at a time but it will not force you to hit enter which is the cause for the new line.
static void Main()
{
char h1, h2, m1, m2;
Console.Write("Enter Time (HH:MM) = ");
h1 = Console.ReadKey().KeyChar;
h2 = Console.ReadKey().KeyChar;
Console.Write(":");
m1 = Console.ReadKey().KeyChar;
m2 = Console.ReadKey().KeyChar;
}
I will leave the actual value parsing as an exercise.
Related
By Input i mean Console.ReadLine() and the way it got changed.
I tried to make a code that could count the days that the User inputed left in the same Year.
After that it should it should loop through the for loop.
This is what it should do.
The Output should be: The difference between the two Inputs, the amount of days it takes to end the year with the first Input in mind subtract that with the total amount and if it is more then 360 it should output the amount and subtract it with 360 so long until the it is under 360.
My Current Output is: 0 Days when numberOfDays is Outputed and when NumberOfDays2 is outputed the Output is 363.
My Problem is that i dont know what exactly the problem is in my Code.
It would be a great help if someone could explain to me where the Problem is or what the root of the Problem is.
Rightnow im very confused do to the comparison with my other code i made where parts like (.TotalDays) perfectly worked.
I would like to know why it doesnt work because in theory it should work.
internal class Program
{
static void Main(string[] args)
{
//Input and Visual
Console.WriteLine("write here Beginning");
Console.Write("Day: ");
string FirstDay = Console.ReadLine();
Console.Write("Month:");
string StillFirstDay = Console.ReadLine();
Console.Write("Year:");
string Still_FirstDay = Console.ReadLine();
Console.Clear();
Console.WriteLine("Beginn: " + FirstDay + "." + StillFirstDay + "." + Still_FirstDay);
Console.WriteLine("");
Console.WriteLine("write here End ");
Console.Write("Day: ");
string LastDay = Console.ReadLine();
Console.Write("Monat:");
string StillLastDay = Console.ReadLine();
Console.Write("Jahr:");
string Still_LastDay = Console.ReadLine();
//Prepare
int input = 0;
int IFirstDay = 1;
int IStillFirstDay = 1;
int IStill_FirstDay = 1;
int ILastDay = 1;
int IStillLastDay = 1;
int IStill_LastDay = 1;
JustforConversion(FirstDay, input, IFirstDay);
JustforConversion(StillFirstDay, input, IStillFirstDay);
JustforConversion(Still_FirstDay, input, IStill_FirstDay);
JustforConversion(LastDay, input, ILastDay);
JustforConversion(StillLastDay, input, IStillLastDay);
JustforConversion(Still_LastDay, input, IStill_LastDay);
DateTime date1 = new DateTime(IStill_LastDay, IStillLastDay, ILastDay);
DateTime date2 = new DateTime(IStill_FirstDay, IStillFirstDay, IFirstDay);
var numberOfDays = (date2 - date1).TotalDays;
Console.WriteLine(numberOfDays);
int Year = IStill_FirstDay - IStill_LastDay;
DateTime date3 = new DateTime(IStillFirstDay, 12, 30);
var numberOfDays1 = (date3 - date2).Days;
Console.WriteLine(numberOfDays1);
var numberOfDays2 = numberOfDays - numberOfDays1;
Console.WriteLine("In Year 1 there were " +numberOfDays1+" Days.");
for (int i = 2; i <= Year; i++)
{
if (numberOfDays2 > 360)
{
Console.WriteLine("In Year " + i + " there were " + numberOfDays2 + " Days.");
numberOfDays2 -= 360;
}
else
{
Console.WriteLine(numberOfDays2);
break;
}
}
Console.ReadKey();
}
static void JustforConversion(string Converted,int Zero,int Complete_Convert)
{
while (int.TryParse(Converted, out Zero))
{
Complete_Convert = Convert.ToInt32(Converted);
break;
}
}
}
}
Your JustforConversion() method has so many things wrong with it, but the biggest problem is that it doesn't actually "return" anything. ints are passed "by value", which means a copy is made; the original variable is NOT changed after the call to JustforConversion().
It looks like you were expecting the "Ixxx" variables to have valid integers in them after the calls. You'd need to declare that parameter as an out parameter for this to work:
static void Main(string[] args)
{
string FirstDay = "10";
int IFirstDay = 1;
Console.WriteLine("Before JustforConversion():");
Console.WriteLine("IFirstDay = " + IFirstDay);
JustforConversion(FirstDay, out IFirstDay);
Console.WriteLine("After JustforConversion():");
Console.WriteLine("IFirstDay = " + IFirstDay);
}
static void JustforConversion(string Converted, out int IConverted)
{
IConverted = int.Parse(Converted);
}
Output:
Before JustforConversion():
IFirstDay = 1
After JustforConversion():
IFirstDay = 10
Task:
The program asks the user to enter the text, after entering the text, the program declares how many words are in the text. It also counts the amount of digits in the text and displays it on the screen.
static void Main(string[] args)
{
Console.Write("Insert text: ");
string s = Console.ReadLine();
int count = 1, num, sum = 0, r;
for (int i = 1; i < s.Length; i++)
{
if (Char.IsWhiteSpace(s[i]))
{
count++;
}
}
num = int.Parse(Console.ReadLine());
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : " + sum);
Console.WriteLine("In text {1} names", s, count);
}
The program asks for the text and numbers to be entered. The numbers in the text are counted why doesnt it work correctly?
As per the input/output described in the comment, You do not need a second ReadLine Statement. You can do as follows.
static void Main(string[] args)
{
Console.WriteLine("Enter Text");
var userEntry = Console.ReadLine();
var countOfWords = userEntry.Split(new []{" "},StringSplitOptions.RemoveEmptyEntries).Count();
var sum = userEntry.Where(c => Char.IsDigit(c)).Select(x=>int.Parse(x.ToString())).Sum();
Console.WriteLine($"Count Of Words :{countOfWords}{Environment.NewLine}Sum :{sum}");
}
This is in the case when(as per your comment), the input string is "xsad8 dlas8 dsao9", for which the sum would be 25.
If the input string is "xsad8 dlas81 dsao9" and you want to treat 81 as '81', rather than 8 & 1, the Sum can be calculated as follows.
var sum = Regex.Split(userEntry, #"\D+").Where(s => s != String.Empty).Sum(x=>int.Parse(x));
Sum in above case would be 98
Try this code. I hope it will help you.
using System;
namespace SimpleProblem
{
class Program
{
static void Main(string[] args)
{
// Task:
// The program asks the user to enter the text, after
// entering the text, the program declares how many words
// are in the text. It also counts the amount of digits in
// the text and displays it on the screen.
Console.WriteLine("Enter a Text");
string word = Console.ReadLine();
int wordCount = 0;
char[] wordsArray = word.ToCharArray();
foreach (var item in wordsArray)
{
//Counting the number of words in array.
wordCount = wordCount + 1;
}
Console.WriteLine("Entered Text: " + word);
Console.WriteLine("No. of Counts: " + wordCount);
}
}
}
My code is as follows:
namespace Calculation
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is a system to calculate speed, distance or time.");
Console.WriteLine("1 = Speed - 2 = Distance - 3 = time");
Console.WriteLine("Please enter which calculation you would like to perform. 1, 2 or 3");
string userCalculation = Console.ReadLine();
int Calculation = int.Parse(userCalculation);
if(Calculation < 1)
{
Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
}
if (Calculation > 3)
{
Console.WriteLine("Please enter a number less than 3 but greater than or equal to 1.");
}
else
{
switch (Calculation)
{
//This statement calculates speed.
case 1:
Console.WriteLine("You have chose to calculate speed. S = D/T");
Console.WriteLine("To work this out you need to firstly enter your distance in metres");
string userDistance = Console.ReadLine();
int Distance = int.Parse(userDistance);
Console.WriteLine("Now enter your time in seconds.");
string userTime = Console.ReadLine();
int Time = int.Parse(userTime);
Console.WriteLine("Your speed is " + Distance / Time + " m/s");
Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
break;
//This statement calculates distance.
case 2:
Console.WriteLine("You have chose to calculate distance. D = SxT");
Console.WriteLine("To work this out you need to firstly enter your speed");
string userSpeed = Console.ReadLine();
int Speed = int.Parse(userSpeed);
Console.WriteLine("Now enter your time in hours.");
string userTime1 = Console.ReadLine();
double Time1 = double.Parse(userTime1);
Console.WriteLine("Your Distance is " + Speed * Time1 + " miles");
break;
//This statement calculates time.
case 3:
Console.WriteLine("You have chose to calculate Time. T = D/S");
Console.WriteLine("To work this out you need to firstly enter your distance in miles.");
string userMiles = Console.ReadLine();
int Miles = int.Parse(userMiles);
Console.WriteLine("Now enter your Speed in MPH.");
string userSpeed2 = Console.ReadLine();
double Speed2 = double.Parse(userSpeed2);
Console.WriteLine("Your Time is " + Miles / Speed2 + "hours.");
Console.WriteLine("This would be " + Miles / Speed2 * 60 + " minutes");
break;
}
}
}
}
}
You can remove one if statement it is not very diffrent from die other if statement. replace it by this one:
if (Calculation < 1 || Calculation > 3)
{
Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
}
Create Two funtions to return user input one for int and the second for the double return type.
private int GetIntUserInput()
{
string userInput = Console.ReadLine();
int convertedUserInput = int.Parse(userInput);
return convertedUserInput;
}
private double GetDoubleUserInput()
{
string userInput = Console.ReadLine();
double convertedUserInput = double.Parse(userInput);
return convertedUserInput;
}
And I should move the calculations to a funtion as well
You also can use an enum for better readability.
enum Options
{
Speed,
Time,
Distance
}
//example
Options calculation = (Options)Calculation; //cast user input number
// to Option enum
switch (calculation)
{
case options.Distance:
// some code
break;
case options.Speed:
// some code
break;
}
First of all, for a better maintainablity index, you better make those 3 algorithms into seperate functions and call them, or at least the calculations.
About the if/switch, you can use a default: case at the end of your switch,
default:
Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
break;
Hope it helped.
As a start, perhaps something like this (air code):
case 1:
Console.WriteLine("You have chose to calculate speed. S = D/T");
int Distance = GetNumericInput("To work this out you need to firstly enter your distance in metres");
int Time = GetNumericInput("Now enter your time in seconds.");
Console.WriteLine("Your speed is " + Distance / Time + " m/s");
Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
break;
Which uses this function (air code, needs error handling):
string GetNumericInput(string prompt)
{
Console.WriteLine(prompt;
string input = Console.ReadLine();
int inputNumeric = int.Parse(input);
return input;
}
My usual approach for organising code like this is to make each case into a class, and add those classes into a dictionary against their case value, e.g.:
public interface ICalculation
{
void Run();
}
public class SpeedCalculation
: ICalculation
{
public void Run()
{
Console.WriteLine("You have chose to calculate speed. S = D/T");
Console.WriteLine("To work this out you need to firstly enter your distance in metres");
string userDistance = Console.ReadLine();
int Distance = int.Parse(userDistance);
Console.WriteLine("Now enter your time in seconds.");
string userTime = Console.ReadLine();
int Time = int.Parse(userTime);
Console.WriteLine("Your speed is " + Distance / Time + " m/s");
Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
}
}
...more ICalculation types...
class Program
{
static void Main(string[] args)
{
var caseDictionary = new Dictionary<int, ICalculation>
{
{1, new SpeedCalculation()},
{2, new DistanceCalculation()},
{3, new TimeCalculation()}
};
Console.WriteLine("This is a system to calculate speed, distance or time.");
Console.WriteLine("1 = Speed - 2 = Distance - 3 = time");
Console.WriteLine("Please enter which calculation you would like to perform. 1, 2 or 3");
string userCalculation = Console.ReadLine();
int Calculation = int.Parse(userCalculation);
if(!caseDictionary.ContainsKey(Calculation))
{
Console.WriteLine("Please enter a number between 1 and 3 (inclusive).");
}
else
{
caseDictionary[Calculation].Run();
}
}
}
This gives you options for organising the code as you like with inheritance or abstractions, makes it easy to add new cases (even programmatically), and you could make the main method more flexible (e.g. the line "1 = Speed - 2 = Distance - 3 = time" could be generated from the contents of the dictionary).
I'd do the following:
class Program
{
private class MenuOption
{
public string Description { get; }
public Action Run { get; }
public MenuOption(string description, Action run)
{
Description = description;
Run = run;
}
}
static void Main(string[] args)
{
int option;
var menuOptions = buildMenuOptions();
do
{
Console.WriteLine($"This is a system to calculate: {string.Join(", ", menuOptions.Values.Take(menuOptions.Count-1).Select(o => o.Description))}");
Console.WriteLine(string.Join(" - ", menuOptions.Select(kv => $"{kv.Key} = {kv.Value.Description}")));
Console.WriteLine($"Please enter which calculation you would like to perform. [{string.Join(", ", menuOptions.Keys)}]");
} while (!tryValidateUserOption(menuOptions, out option));
menuOptions[option].Run();
Console.Write("Press key to exit... ");
Console.ReadKey();
}
private static IDictionary<int, MenuOption> buildMenuOptions() =>
new Dictionary<int, MenuOption>() { { 1, new MenuOption("Speed", () => runSpeedOption()) },
{ 2, new MenuOption("Distance", () => runDistanceOption()) },
{ 3, new MenuOption("Time", () => runTimeOption())},
{ 4, new MenuOption("Quit", () => { return; }) } };
private static bool tryValidateUserOption(IDictionary<int, MenuOption> options, out int selectedOption)
{
var input = Console.ReadLine();
if (!int.TryParse(input, out selectedOption) ||
!options.ContainsKey(selectedOption))
{
Console.WriteLine("Invalid option. Please try again.");
return false;
}
return true;
}
private static void runTimeOption()
{
int miles;
double speed;
Console.WriteLine("You have chose to calculate Time. T = D/S.");
getUserInput("To work this out you need to firstly enter your distance in miles.", 0, int.MaxValue, out miles);
getUserInput("Now enter your Speed in MPH.", 0, double.MaxValue, out speed);
Console.WriteLine("Your Time is " + miles / speed + " hours.");
Console.WriteLine("This would be " + miles / speed * 60 + " minutes");
}
private static void runDistanceOption()
{
int speed;
double time;
Console.WriteLine("You have chose to calculate distance. D = SxT.");
getUserInput("To work this out you need to firstly enter your speed.", 0, int.MaxValue, out speed);
getUserInput("Now enter your time in hours.", 0, double.MaxValue, out time);
Console.WriteLine("Now enter your time in hours.");
Console.WriteLine("Your Distance is " + speed * time + " miles");
}
private static void runSpeedOption()
{
int distance, time;
Console.WriteLine("You have chose to calculate speed. S = D/T");
getUserInput("To work this out you need to firstly enter your distance in metres.", 0, int.MaxValue, out distance);
getUserInput("Now enter your time in seconds.", 0, int.MaxValue, out time);
Console.WriteLine("Your speed is " + distance / time + " m/s");
Console.WriteLine("In MPH this is " + distance / time * 2.23 + " MPH");
}
private static void getUserInput(string message, int lowerInclusiveBound, int upperExclusiveBound, out int value)
{
while (true)
{
Console.WriteLine(message);
var input = Console.ReadLine();
if (int.TryParse(input, out value) &&
value >= lowerInclusiveBound &&
value < upperExclusiveBound)
return;
Console.WriteLine("Input is not a valid value. Please try again.");
}
}
private static void getUserInput(string message, double lowerInclusiveBound, double upperExclusiveBound, out double value)
{
while (true)
{
Console.WriteLine(message);
var input = Console.ReadLine();
if (double.TryParse(input, out value) &&
value >= lowerInclusiveBound &&
value < upperExclusiveBound)
return;
Console.WriteLine("Input is not a valid value. Please try again.");
}
}
}
Things to note:
Don't hard code the menu. Make it flexible, that way adding options is easy; look how much it took to add a fourth option.
If the menu is not set, you can't hard code options with ifs and switches. Use a dictionary with the option number as a key. Store as value a delegate to the action you want to perform.
Try to not repeate code. Extract all common functionality to helper methods that can be reused; consider changing all inputs to double to reduce pesky code duplication validating ints and doubles.
I am trying to create a program for a hotel where the user is to enter a character (either S, D, or L) and that is supposed to correspond with a code further down the line. I need help converting the user input (no matter what way they enter it) to be converted to uppercase so I can then use an if statement to do what I need to do.
My code so far is the following:
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
**^Right Her is Where I Want To Convert To Uppercase^**
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
public static double RoomCharge(int NumDays, char RoomType)
{
double Charge = 0;
if (RoomType =='S')
Charge = NumDays * 80.00;
if (RoomType =='D')
Charge= NumDays * 125.00;
if (RoomType =='L')
Charge = NumDays * 160.00;
Charge = Charge * (double)NumDays;
Charge = Charge * 1.13;
return Charge;
}
Try default ToUpper method.
roomtype = Char.ToUpper(roomtype);
Go through this http://msdn.microsoft.com/en-us/library/7d723h14%28v=vs.110%29.aspx
roomtype = Char.ToUpper(roomtype);
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
roomtype = Char.ToUpper(roomtype);
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
this is my first post, apologies for mistakes I may make and bad formatting.
The issue I am having is that the second time it loops
int whichAccount = int.Parse(Console.ReadLine()); does not work and won't take my input. It raises the exception "Input string was not in a correct format". The first time it loops it all works fine. What is am I doing wrong? Thanks.
class ATM
{
const int SAVING_ACCOUNT = 1;
const int DEBIT_CARD = 2;
const int CREDIT_CARD = 3;
const int INVESTMENT_ACCOUNT = 4;
static double[] accountBalances = { 0.0, 1001.45, 850.0, -150.0, 10000.0 };
static string[] accountNames = { "", "Savings Account", "Debit Card",
"Credit Card", "Investment Account" };
static void Main()
{
char y;
do {
Console.Write("\tSAVING_ACCOUNT = 1;\n\tDEBIT_CARD = 2;\n\tCREDIT_CARD = 3;\n\tINVESTMENT_ACCOUNT = 4;\n\nPlease select account: ");
int whichAccount = Int32.Parse(Console.ReadLine());
DisplayBalance(whichAccount);
Console.Write("\nDo you wish to see the balance of another account? Y/N: ");
y = (char)Console.Read();
} while (Char.IsLetter(y));
}
static void DisplayBalance(int whichAccount)
{
switch (whichAccount)
{
case 1: Console.WriteLine("\nAccount Balance of Savings Account = ${0}", accountBalances[1]);
DateTime date = DateTime.Now;
Console.WriteLine("Current Date: {0} ", date );
break;
case 2: Console.WriteLine("{0}", accountBalances[2]);
break;
case 3: Console.WriteLine("{0}", accountBalances[3]);
break;
case 4: Console.WriteLine("{0}", accountBalances[4]);
break;
}
}
The problem is due to y = (char)Console.Read();
Consider using the following to read the first character in the input. It will ensure the entire input is read which will not leave any additional characters or empty spaces in the remaining console text:
y = Console.ReadLine().Trim()[0];