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
Related
i'm a beginner to c#,so i was trying to make a program that rolls a die for you and the enemy for 10 turns,each turns adding the number of your roll to an overall count and whoever got the largest in the end won,i didn't finish it all the way but this is what i have so far:
namespace dfgs
{
class dice
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 11)
{
Console.WriteLine("Player Roll Is" + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is" + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd;
aisc = aisc + airnd;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
Console.ReadLine();
}
}
}
}
and whenever i try to compile i get the error Operator +' cannot be applied to operands of type int' and System.Random',this error appears twice,i tried changing the type of the random numbers to int but then i got the error messege Type int' does not contain a definition for Next' and no extension method Next' of type int' could be found. Are you missing an assembly reference? i am kinda stuck here,any help would be appreciated.
EDIT:Thank you to everyone who answered, i have managed to make this work,here is the final code,it's not the cleanest but works as intended:
namespace dfgs
{
class die
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 10)
{
Console.WriteLine("Player Roll Is " + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is " + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd.Next(6);
aisc = aisc + airnd.Next(6);
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
else{
break;
}
if (turns == 10){
if (plsc > aisc){
Console.WriteLine("The Player Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
else if (aisc > plsc){
Console.WriteLine("The AI Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
break;
}
}
Console.ReadLine();
}
}
}
You probably want to save the random int you get from the Random, rather than trying to calculate number, plus a random_number_generator_machine - which, in some real world terms would be like asking someone "what is your age, divided by a cheese sandwich?"..
var plroll = plrnd.Next(6);
var airoll = airnd.Next(6);
Console.WriteLine("Player Roll Is" + plroll);
Console.WriteLine("AI Roll Is" + airoll));
plsc = plsc + plroll;
aisc = aisc + airoll;
You don't need a Random for the player and a Random for the computer; one Random could adequately generate for both, btw:
int plsc = 0;
int aisc = 0;
int turns = 0;
Random r = new Random();
while (turns < 11)
{
var plroll = r.Next(6);
var airoll = r.Next(6);
Console.WriteLine("Player Roll Is" + plroll);
Console.WriteLine("AI Roll Is" + airoll));
plsc = plsc + plroll;
aisc = aisc + airoll;
Look at this line:
plsc = plsc + plrnd;
In this code, plrnd is not a number. Instead, it's a generator for producing numbers. You must tell the generator to give you the next number, as you did on the line above:
plrnd.Next(6)
Moreover, you likely need to change the code above to save the results of each call in variables so you can use that same value to both show to the user and increment the total count.
Since you want to use the result of the roll multiple times, start by assigning the results to a variable for later use:
while (turns < 11)
{
// roll dies, store results in local variable
var plRoll = plrnd.Next(6);
var aiRoll = airnd.Next(6);
// then reuse the variables
Console.WriteLine("Player Roll Is " + plRoll);
Console.WriteLine("AI Roll Is " + aiRoll);
plsc = plsc + plRoll;
aisc = aisc + aiRoll;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
else {
// remember to break out if the player doesn't want to continue
break;
}
}
int is a built in value data type in C#. Random is a class object. The + operator does not know how to add an int data type and a Random class object together. What you probably meant to do is to use the Next() method, which does return an int. Also, you only want to new up the Random class one time. Consider using this code instead:
namespace dfgs
{
class dice
{
public static void Main(String[] args)
{
Random rnd = new Random();
int plsc = 0;
int aisc = 0;
int turns = 0;
int plrnd = rnd.Next(6);
int airnd = rnd.Next(6);
while (turns < 11)
{
Console.WriteLine("Player Roll Is" + plrnd);
Console.WriteLine("AI Roll Is" + airnd);
plsc = plsc + plrnd;
aisc = aisc + airnd;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
Console.ReadLine();
}
}
}
}
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);
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.
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
}
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