C# Console.WriteLine is not called from a method - c#

I've just started studying the C#. And bumped into a problem:
When I use the Console.WriteLine in the Main method, it works just fine. However, when I try to break the code into methods, the WriteLine does not return anything. (I use Visual Studio to build and compile the project).
The task is to find a final amount of money a person would get when depositing money based on monthly capitalization. I kinda suspect I just messed up some trivial thing, but would still appreciate an explanation :) Thanks
The code without methods:
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
//Separating the input string into substrings
string[] separated = userInput.Split(' ');
//Getting the main variables
double sum1 = double.Parse(separated[0]);
double oneMonthPercentage = double.Parse(separated[1]) / 1200; //find a montly amount in percent = amount / 12 month / 100
double months = double.Parse(separated[2]);
double initialSum = sum1;
//Calculation of the final ammount
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
}
}
OUTPUTS - no_methods
The code with methods (WriteLine does not work):
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
}
//Separating string into substrings
public static string[] SeparateString(string userInput)
{
string[] separated = userInput.Split(' ');
return separated;
}
//calculating the final amount at the end of deposit time
public static double Calculate(string userInput)
{
// defining main variables for calculation
double sum1 = double.Parse(SeparateString(userInput)[0]);
double oneMonthPercentage = double.Parse(SeparateString(userInput)[1]) / 1200;
double months = double.Parse(SeparateString(userInput)[2]);
double initialSum = sum1;
//calculation as to the formula
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
return sum1;
}
}
OUTPUTS - with_methods

You need to call those methods to make them work. Right now you are only calling the initial WriteLine and ReadLine

You don't call any method. You should call Calculate() method:
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
var result = Calculate(userInput); // call here
}

Related

How can i succesfully convert to a spefic Time and use .TotalDays?

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

My Code is a c# randomly generated math quiz i need to show the result of the correct and wrong answer of the user at the end

I could not do it with storing the user question as a string because of the loop because I need the result at the end I'm new to programming I need help the code is mostly done it is just the result part I'm having problems with I tried with using a string and store the user question but I couldn't find out how to store random generated questions in it.
using System;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Threading;
namespace bpg401project_homework_1
{
class MainClass
{
public static void Main(string[] args)
{
Random randomgen = new Random();
Stopwatch stopWatch = new Stopwatch();
int a; TimeSpan xs = stopWatch.Elapsed; string Sa = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
xs.Hours, xs.Minutes, xs.Seconds,
xs.Milliseconds / 10); ; float p;
//asking the user for max limit of time
Console.Write("how much time(min) : ");
Sa = Console.ReadLine(); a = Int32.Parse(Sa);
Thread.Sleep(a);
// start Time
stopWatch.Start();
// generating random numbers
int num01 = randomgen.Next(10,50);
int num02 = randomgen.Next(10,100);
int useranswer;
int answer;
int numofquestions;
int numofquestionsleft;
int numofcorrect = 0;
//asking the user for max limit of questions
Console.Write("Max Question : ");
numofquestions = Convert.ToInt32(Console.ReadLine());
numofquestionsleft = numofquestions;
// This is the loop that handles the actual question/answer of the quiz.
while (numofquestionsleft > 0)
{
// the question
Console.Write("What is " + num01 + " / " + num02 + "? ");
answer = num01 % num02;
useranswer = Convert.ToInt32(Console.ReadLine());
// mines the question the have been left -1
numofquestionsleft--;
num01 = randomgen.Next(10,50);
num02 = randomgen.Next(10,100);
}
// the user answer score
Console.WriteLine("You got " + numofcorrect + " of " + numofquestions + " correct!");
// Format and display the TimeSpan value
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
// letting the user know how much time did they take.
Console.WriteLine("RunTime " + elapsedTime);
// letting the user know if they made it on time
if (xs > ts)
{
Console.WriteLine("Sorry time is up , try again");
}
else
{
Console.WriteLine(" you made it on time");
}
Console.ReadKey();
}
}
}
Declare a QuestionAnswer class:
public class QuestionAnswer
{
public string Question {get;set;}
public int Answer {get;set;}
}
Modify your code to declare a List of type QuestionAnswer at the start of your program:
Random randomgen = new Random();
List<QuestionAnswer> questionAnswers = new List<QuestionAnswer>();
Stopwatch stopWatch = new Stopwatch();
In your while loop store the question and answer in questionAnswer type and then add to the list:
// the question
QuestionAnswer questionAnswer = new QuestionAnswer();
questionAnswer.Question = "What is " + num01 + " / " + num02 + "? ";
Console.Write(questionAnswer.Question);
...
questionAnswer.Answer= Convert.ToInt32(Console.ReadLine());
//store the question / answer in list
questionAnswers.Add(questionAnswer);

If and Switch statements; Is there an easier way of producing this code?

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.

C# launch a program with mandatory parameters and optional parameters from cmd

I need to call a program from cmd using an array of numbers(mandatory) and an int time(optional). I have never done this so i'm a bit shaky on the details.
The path is D:\Robert\FactorialConsoleApplication\FactorialConsoleApplication\bin\Debug\FactorialConsoleApplication.exe
As you can tell, the program calculates the factorial of the numbers in the array. The int time is used as a delay in order to display the progress of the stack.
How do I call the program with parameters?
Thanks in advance!
P.S. Here is some of the code
class Program
{
public static void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue ;
double max = System.Convert.ToDouble(numbers[j]);
System.Convert.ToDouble(stack_value);
double percent = (stack_value / max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
public static void Calculate(int number, int time=0)
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(number, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + number + " is : " + Result);
Console.ReadLine();
}
static int j;
static int[] numbers;
public static void Main(string[] args)
{
int i=0;
bool ok = false;
string line = string.Empty;
numbers = new int[10];
Console.Write("Please insert wait time (0,1 or 2) : ");
int time = int.Parse(Console.ReadLine()) * 1000;
Console.Write("Please insert a number : ");
do
{
line = Console.ReadLine();
if (line != "")
{
i++;
numbers[i] = int.Parse(line);
}
else
{
ok = true;
}
}
while (ok == false);
for (j = 1; j <= i; j++)
{
Calculate(numbers[j],time);
}
}
}
In .net you can use Process.Start from System.Diagnostics to launch an application, you can pass parameters too
For example Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm"); will open Internet Explorer and pass the value "C:\\myPath\\myFile.htm" as parameter to it.For more examplles check the MSDN article on Process.Start method
Update
If in case you are looking to take parameters to your application, when launching itself you don't have to do anything, you are already doing that, the parameter args in your Main method will hold the arguments passed to your application, just try and parse those values in the args array to int array and you are good to go.
Ok, so here is the solution.
I used an args parser like this :
static int extra;
public static void Main(string[] args)
{
foreach (string s in args)
{
extra = int.Parse(s);
Calculate(extra);
}
}
And I changed :double max = System.Convert.ToDouble(numbers[j]);
to :double max = System.Convert.ToDouble(extra);
To call it I open cmd in the directory where the exe is and I type :
Program.exe 3 4 5
It will calculate the factorials of 3, 4 and 5 respectively

C# bowling array program

So I am having problems with programming a bowling application in c# to calculate 5 different scores, storing them in an array and returning the average, highest and lowest scores, I am having problems with the code for storing the array and returning the scores. Here is what i have so far:
static void Main(string[] args)
{
//Declarations
const double MIN_SCORE = 0;
const double MAX_SCORE = 300;
const int SCORE_COUNT = 5;
int[] scores = new int[SCORE_COUNT]; //stores all the scores
int inputScore; //stores one score
double total = 0; //to total the scores for average
double average; //average the grades
double highScore; //highest score of the games
double lowScore; //lowest score of the games
//INPUT
//loop to get scores
for (int bowler = 0; bowler < scores.Length; bowler++)
{
try
{
//prompt for and get the input
Console.Write("Please enter score for game " + (bowler + 1) + ":");
inputScore = Convert.ToInt16(Console.ReadLine());
//valid range?
if (inputScore > MAX_SCORE || inputScore < MIN_SCORE)
{
Console.WriteLine("Scores must be between " + MIN_SCORE +
" and " + MAX_SCORE + ". Please try again. ");
bowler--;
}
else
{
scores[bowler] = inputScore;
}
}
catch (Exception myEx)
{
Console.WriteLine(myEx.Message + " Please try again. ");
bowler--;
}
//PROCESS
Array.Sort(scores);
//OUTPUT
Console.WriteLine("\n\nAverage Score for Bowler:{0}");
}
}
Add this using statement:
using System.Linq;
Then you can use:
scores.Average();
scores.Max();
scores.Min();
Simple enough.

Categories