Currently i wanna display the following variable
Total Item
Total Execution
Finish Status
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
int TotalValue = 250; // Total Item Example
int TotalExecution = 0;
bool Finish_Status = false;
for (int i = 0; i < TotalValue; ++i)
{
//Do Work Here
System.Threading.Thread.Sleep(10); // Example Work
TotalExecution++;
if (TotalValue - TotalExecution == 0)
{
Finish_Status = true;
}
Console.Clear();
Console.Write("Progression Info\n Total Item : {0}\n Execution Total : {1}\n Remaining : {2}\n Finish_Status : {3}", TotalValue,TotalExecution, TotalValue - TotalExecution, Finish_Status); // Display Information To Console
}
Console.ReadLine();
}
}
}
The result is good,however i was wondering if theres a much more efficient way of doing this,preferably updating it without using Console.Clear();
You can use Console.SetCursorPosition to move the cursor around the console buffer for each write, rather than clearing the console each time.
For example:
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
int TotalValue = 250; // Total Item Example
int TotalExecution = 0;
bool Finish_Status = false;
Console.Write("Progression Info\n Total Item : \n Execution Total : \n Remaining : \n Finish_Status : ");
for (int i = 0; i < TotalValue; ++i)
{
//Do Work Here
System.Threading.Thread.Sleep(10); // Example Work
TotalExecution++;
if (TotalValue - TotalExecution == 0)
{
Finish_Status = true;
}
Console.SetCursorPosition(26, 1);
Console.Write(TotalValue);
Console.SetCursorPosition(31, 2);
Console.Write(TotalExecution);
Console.SetCursorPosition(25, 3);
Console.Write(TotalValue - TotalExecution);
Console.SetCursorPosition(29, 4);
Console.Write(Finish_Status);
}
Console.ReadLine();
}
}
}
Disclaimer: Obviously the above is quick 'n' dirty, and would benefit from substantial refinement, but you get the idea.
Welcome kepanin_lee
I think you are looking for something like this.
//Console.Clear()
Console.Write(vbCr & "Progression Info\n...
Just start with vbCr, by this way you force to start on the beginning of the same line, so you only overwrite the last line, without clear all the screen.
Related
so we can give any number of parameters to a method, like this:
static int sumPrices(params int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
int total = sumPrices(100, 50, 200, 350);
Console.WriteLine(total);
Console.ReadKey();
}
but ... what if we wanted to get the "100, 50, 200, 350" from the USER?
in above example it's the coder giving the sumPrices method its arguments/parameters.
i mean, it would be one solution to just pass the method an array.
static int sumPrices(int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
//get up to 9999 inputs and sum them using a method
bool whileLoop = true;
int[] inputs = new int[9999];
int index = 0;
while (whileLoop == true)
{
Console.WriteLine("entering price #" + index + ", type 'stop' to sum prices");
string check = Console.ReadLine();
if (check == "stop") {
whileLoop = false;
break;
}
inputs[index] = int.Parse(check);
index++;
}
int[] prices = new int[index];
for (int i = 0; i < index; i++)
{
prices[i] = inputs[i];
}
Console.WriteLine("-----------------");
Console.WriteLine(sumPrices(prices));
Console.ReadKey();
}
BUT... longer code... and has limits.
our professor basically wanted the first code, however, i don't see how and where it's
supposed be used if we didn't know the user's inputs and if params arguments were coming from the coder (unless of course, coder using the same function multiple times for convenience)
i have tried to think of a solution and i'm not exactly sure how it could be done.
but it basically goes like this.
we could get inputs from the user separated by commas:
100,200,50
and the program would translate it into params arguments:
sumPrices("100,200,50");
but as you can see... it's a string. i wonder if there's a JSON.parse() thing like in js.
The code in the OP has some unnecessary code as well as some limitations such as 9999.
Let's examine the following code:
bool whileLoop = true;
while (whileLoop == true)
{
}
This could be re-written as:
while (true == true)
{
}
or
while (true)
{
}
Next, let's examine the following code:
if (check == "stop") {
whileLoop = false;
break;
}
You've set whileLoop = false; which is unnecessary because once break is executed, excution has moved to after the loop.
Since the input array has a hard-code size of 9999, you've limited yourself to 9999 values. You may consider using a List instead or resize the array.
Try the following:
using System;
using System.Collections.Generic;
using System.Linq;
namespace UserInputTest
{
internal class Program
{
static void Main(string[] args)
{
decimal price = 0;
List<decimal> _values = new List<decimal>();
if (args.Length == 0)
{
//prompts for user input
Console.WriteLine("The following program will sum the prices that are entered. To exit, type 'q'");
do
{
Console.Write("Please enter a price: ");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q")
break; //exit loop
else if (Decimal.TryParse(userInput, out price))
_values.Add(price); //if the user input can be converted to a decimal, add it to the list
else
Console.WriteLine($"Error: Invalid price ('{userInput}'). Please try again.");
} while (true);
}
else
{
//reads input from command-line arguments instead of prompting for user input
foreach (string arg in args)
{
if (Decimal.TryParse(arg, out price))
{
//if the user input can be converted to a decimal, add it to the list
_values.Add(price); //add
}
else
{
Console.WriteLine($"Error: Invalid price ('{arg}'). Exiting.");
Environment.Exit(-1);
}
}
}
Console.WriteLine($"\nThe sum is: {SumPrices(_values)}");
}
static decimal SumPrices(List<decimal> prices)
{
return prices.Sum(x => x);
}
static decimal SumPricesF(List<decimal> prices)
{
decimal sum = 0;
foreach (decimal price in prices)
sum += price;
return sum;
}
}
}
Usage 1:
UserInputTest.exe
Usage 2:
UserInputTest.exe 1 2 3 4 5
Resources:
Built-in types (C# reference)
Floating-point numeric types (C# reference)
Decimal.TryParse
Iteration statements - for, foreach, do, and while
String interpolation using $
List Class
Enumerable.Sum Method
Default values of C# types (C# reference)
Environment.Exit
The trick is input from the user always starts out as strings. You must parse those strings into integers. We can do it in very little code like this:
static int sumPrices(IEnumerable<int> prices)
{
return prices.Sum();
}
static void Main(string[] args)
{
int total = sumPrices(args.Select(int.Parse));
Console.WriteLine(total);
Console.ReadKey();
}
See it here (with adjustments for the sandbox environment):
https://dotnetfiddle.net/Pv6B6e
Note this assumes a perfect typist. There is no error checking if a provided value will not parse.
But I doubt using linq operations are expected in an early school project, so we can expand this a little bit to only use techniques that are more familiar:
static int sumPrices(int[] prices)
{
int total = 0;
foreach(int price in prices)
{
total += price;
}
return total;
}
static void Main(string[] args)
{
int[] prices = new int[args.Length];
for(int i = 0; i<args.Length; i++)
{
prices[i] = int.Parse(args[i]);
}
int total = sumPrices(prices);
Console.WriteLine(total);
Console.ReadKey();
}
If you're also not allowed to use int.Parse() (which is nuts, but sometimes homework has odd constraints) you would keep everything else the same, but replace int.Parse() with your own ParseInt() method:
static int ParseInt(string input)
{
int exponent = 0;
int result = 0;
for(int i = input.Length -1; i>=0; i--)
{
result += ((int)(input[i]-'0') * (int)Math.Pow(10, exponent));
exponent++;
}
return result;
}
Again: there's no error checking here for things like out-of-bounds or non-numeric inputs, and this particular implementation only works for positive integers.
this might be a simple/dumb question but I'm trying to figure out why my code keeps returning 0. I don't think my syntax for passing the value is correct but I cant figure out the proper way of doing it.
class ICESMARK
{
static int ICECount = 0;
public double average = 0;
public double[] ICES = new double[8];
public ICESMARK(double Mark)
{
Mark = ICES[ICECount];
if (ICECount == (ICES.Length - 1))
{
for (int x = 0; x < ICES.Length; x++)
{
average += ICES[x];
}
average /= ICES.Length;
}
ICECount++;
}
}
class Program
{
static void Main(string[] args)
{
ICESMARK[] ICE = new ICESMARK[8];
//LABSMARK[] LAB = new LABSMARK[6];
double userInput;
for (int counter = 0; counter < ICE.Length ; counter++)
{
Console.Write("Please enter your mark for ICE{0}: ", counter + 1 );
bool ifInt = double.TryParse(Console.ReadLine(), out userInput);
ICE[counter] = new ICESMARK(userInput);
}
Console.WriteLine(ICE[1].average);
Console.ReadLine();
}
}
ICE[1].average - Displays 0
Also if anyone has a more efficient way of doing this, feel free to let me know. Except for the average, is gotta be a calculation, cant use the built in method.
Simplest code to get your work done:
void Main()
{
double[] ICE = new double[8];
double userInput = 0.0;
for (int counter = 0; counter < ICE.Length; counter++)
{
Console.WriteLine($"Please enter your mark for ICE {counter}: ");
bool isNumerical = false;
while(!isNumerical)
isNumerical = double.TryParse(Console.ReadLine(), out userInput);
ICE[counter] = userInput;
}
Console.WriteLine("Average : " + ICE.Average());
Console.ReadLine();
}
How it works:
Removed all the frills, you don't need an extra class just for this purpose
Made it mandatory for code to enter valid double value to fill all the slots
Finally used Linq Average to calculate Average value
I want to clarify that yes there are easier ways to solve this, but the entire point of the project was to use a class and it specifically says I cant use built in methods such as "array.average".
Sorry that my code was super messy, I was honestly all over the place and very confused. Having that said I finally arrived to this solution. Thanks to everyone who tried to help! really appreciate it, some tips here were very helpful in solving and cleaning up my code.
class ICESMARK
{
public static int ICECount = 0;
public static double average = 0;
public ICESMARK(double Mark)
{
average += Mark;
if (ICECount < 8) { ICECount++; }
if (ICECount == 8) { average /= ICECount;}
}
}
class Program
{
static void Main(string[] args)
{
ICESMARK[] ICE = new ICESMARK[8];
double userInput;
for (int counter = 0; counter < ICE.Length ; counter++)
{
Console.Write("Please enter your mark for ICE{0}: ", counter + 1 );
bool ifInt = double.TryParse(Console.ReadLine(), out userInput);
ICE[counter] = new ICESMARK(userInput);
Console.WriteLine(ICESMARK.ICECount);
}
Console.WriteLine(ICESMARK.average);
Console.WriteLine(ICESMARK.ICECount);
Console.ReadLine();
}
}
I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:
I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.
My factorial calculator isn't working quite correctly.
It works as expected from 1 to 20, as my professor wants. However, entering 0 should return a factorial of 1; it returns 0
Here is my code:
private void CalculateFactorial(long number)
{
//perform the calculations
long result = number;
for (int i = 1; i < number; i++)
{
result = result * i;
}
//display the calculated Factorial to the user
txt_Factorial.Text = result.ToString("n0");
}
Here is the method which calls the above method, the event handler for the calculate button:
private void btn_Calculate_Click(object sender, EventArgs e)
{
//get the users input
long number = long.Parse(txt_Number.Text);
// make sure the number not invalid. If it is invalid, tell the user
// otherwise, proceed to calculation.
if (number < 0 || number > 20)
txt_Factorial.Text = "Invalid Number";
else
CalculateFactorial(number);
txt_Number.Focus(); // returns the focus to the number box whether or not data was valid
Ideas?
If you step through this in a debugger the problem becomes pretty clear. And as you're just getting started with programming I highly recommend getting used to a debugger as early as you can. It's an absolutely invaluable tool for programming.
Look at your for loop:
for (int i = 1; i < number; i++)
What happens when number is 0? The loop never runs. You can't include 0 in the loop range because that would set every result to 0 by first multiplying it by 0. So you need to add an explicit check for 0 in the function logic:
if (number == 0)
return 1;
// continue with your loop here
Factorial of 0 is 1 by definition, not by calculation, and your code does not reflect that. Add a check before your code:
if (number == 0)
result = 1;
else
// compute factorial
Also think about creating a function that returns an integer value as the result.
You can use this :
if(number == 0){
result = 1;
}
for (int i = 1; i <= number; i++)
result *= i;
}
also your formula is wrong because n! = 1*2*3*.....*n
You can test the following code! tested and works. Recursive Implementation as well as basic implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}