I can't figure out how to pass total, sale and comm into Main().
Anybody got an idea how to get those variables into Main and display (output) them there with the names?
Right now I can just output the variables in calcComm ...
Thanks in advance
Philip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
}
calcComm(total);
}
public static void calcComm(double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
public static void Main ()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
string name;
Console.WriteLine("Please enter intial or type 'z' to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
}
else if (Letter == 'b')
{
name = name2;
getsales();
}
else if (Letter == 'e')
{
name = name3;
getsales();
}
else
{
Console.WriteLine("Invalid entry try again");
}
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
}
}
}
}
This gives an array of strings corresponding to the command line parameters.
Main(string [] args)
By the way, when dealing with monetary units, it's better to use decimal than double.
You should be using objects, then you can make those public.
class Sales
{
public double total;
public double sale;
public double comm;
...
public void CalcComm()
{
...
}
}
Then you can reference them like this:
Sales.total, Sales.sale
Or you can make them global but that's not normally advisable.
Look into the return keyword in C#; get your functions to return the relevant data back to main and have it make use of it.
Consider this example for how to add command line arguments. If you need them to be programmatically added consider writing a wrapper program and starting the Process inside it.
using System;
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
}
Console.ReadLine();
}
}
either you can build up a Data Transfer Object that holds all these three variables instantiate it and then return it to your main function.
You could also make use of variables that are passed as references instead of by value and use the updated reference value. Read about pass by value type & reference type for c# and the ref keyword.
Related
when I enter 1 for n
and 1111 for lines
the sum must be 1+1+1+1=4 but the output is 1.
THIS IS THE QUESTION...
you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.
using System;
namespace prom2
{
class Program
{
static void Main(string[] args)
{
int lines=0, sum = 0;
Console.Write("Enter a number of lines ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n&n>0&1000>n; i++)
{
Console.WriteLine("Enter line " + i + " numbers");
lines = int.Parse(Console.ReadLine());
lines = lines / 10;
sum += lines % 10;
Console.WriteLine("sum is " + sum);
}
}
}
}
Try this:
static void Main(string[] args)
{
int input;
bool times = true;
List<int> numbers = new List<int>();
while (times)
{
Console.Clear();
Console.WriteLine("Enter number: ");
var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
if (num)
{
numbers.Add(input);//only integers will be added to list
}
Console.Clear();
Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
var yesno = Console.ReadLine();//get answer from user
if (yesno.ToUpper().Trim() != "Y")//if N or anything else
{
//assume no
times = false;
}
Console.Clear();
}
var sum = numbers.Sum();
Console.WriteLine("Sum : " + sum.ToString());
Console.ReadLine();//just to pause screen
}
Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.
If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.
Edit
My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.
Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):
using System;
using Xunit;
namespace StackOverflow71442136SumDigits
{
public class UnitTest1
{
[Theory]
[InlineData("1", 1)]
[InlineData("12", 3)]
[InlineData("23", 5)]
[InlineData("1234", 10)]
[InlineData("123456789", 45)]
public void Test1(string line, int expectedSum)
{
var actualSum = this.SumTheDigits(line);
Assert.Equal(expectedSum, actualSum);
}
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
}
}
You might want to read How do I ask and answer homework questions?
My goal is to make a math expression interpreter with c#, for example if you type "A=3", it'll save the A as a dictionary key and 3 as its value, this program has more features so if you type "B=3" and then "A=B+3" and then "Show(A)", it must display "6" as the answer.
Everything is right until I type something like "A=10" "B=10" "C=A+B" and finally "Show(C)", because Variables' value are 2-digit (or more) numbers in this case, when producing the final result, numbers are saved in the string like "01+01" instead of "10+10" (because A and B values are 10 so A+B should be 10+10), so it's kinda reversed.
I tried to reverse the string and then evaluate the answer but that didn't work as well, simply it gives me "1+1" for some reason!
Notes:
expression evaluation is done by "return Convert.ToInt32(new DataTable().Compute(result, null));"
because strings are immutable in c#, when every expression like "A+B" or "3+5" comes in the method, I create a new empty string like (string result = " ";) and then with the help of "result = ValidExpression[i] + result.Remove(counter, 0);", I change the variables with values (note = if all the elements of input are numbers, answer is right) like "A" with "23" and put them in the new string and then evaluate the final string. But as I said, it saves the 23 as 32 so the answer will be wrong.
This is my code and the bug is probably in the LongProcessing method.
Thanks for your helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Data;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome To The Program\nCorrect Syntax:");
Console.WriteLine("A=10\nB=15\nC=A+B\nD=13/4-2+A-C+B\nShow(D)");
Console.WriteLine("\nEnter your input:");
Expression E = new Expression();
string expression = "start";
while (expression != "exit")
{
expression = Console.ReadLine();
// for show command
if (expression.Contains("Show") == true)
try { E.Show(expression[5]); }
catch (Exception e)
{
Console.WriteLine("input is not correct, Can not show anything. please try again");
}
if (E.Validation(expression) == false)
Console.WriteLine("input is not correct, please try again");
else
E.Processing(expression);
}
Console.ReadKey();
}
}
class Expression
{
public Dictionary<Char, String> Variables = new Dictionary<Char, String>();
public Expression()
{ }
public Boolean Validation(string expression)
{
// true if c is a letter or a decimal digit; otherwise, false && true if c is a decimal digit; otherwise, false.
if (!Char.IsLetterOrDigit(expression[0]) || Char.IsDigit(expression[0]))
return false;
else
return true;
}
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
// something is wrong in this method
public int LongProcessing(String ValidExpression)
{
string temp;
int counter = 0;
string result = " ";
for (int i = 0; i < ValidExpression.Length; i++)
{
//changing variables (letters) with values
if (Char.IsLetter(ValidExpression[i]))
{
if (Variables.ContainsKey(ValidExpression[i]))
{
Variables.TryGetValue(ValidExpression[i], out temp);
for (int j = 0; j < temp.Length; j++)
{
result = temp[j] + result.Remove(counter, 0);
counter++;
}
}
}
else
{
result = ValidExpression[i] + result.Remove(counter, 0);
counter++;
}
}
// checks if all of the string elements are numbers
if (ValidExpression.All(char.IsDigit))
return Convert.ToInt32(ValidExpression);
else
{
return Convert.ToInt32(new DataTable().Compute(result, null));
}
}
public void Show(Char ValidExpression)
{
Console.WriteLine(Variables[ValidExpression]);
}
}
}
This is broken:
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
temp.Remove(i, 0) is a non op, you might as well just write temp
So let's plot the loop:
Assume ValidExpression is "A=10"
Temp starts out as " "
First iteration, temp is "1 "
Second iteration, temp is "01 "
Any operation that works left to right through a string, character by character, pulling a character out and sticking it on the start of a growing string, will reverse the string
Perhaps you meant to not have a loop and instead do temp = ValidExpression.Substring(2) ?
Here are some suggestions:
Start by looking at the value of "temp" in "Processing". To assist in your debugging, add a "Console.WriteLine" statement.
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
{
temp = ValidExpression[i] + temp.Remove(i, 0);
Console.WriteLine(" temp: " + temp); //added for debugging
}
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
A couple of other things:
The user is never informed how to exit.
There is a class named "Expression" and a string variable named
"expression". This is likely to cause confusion.
You may also want to look at this post: how to convert a string to a mathematical expression programmatically
I wrote a do-while loop but it does not run through while condition somehow.
When I type in invalid characters it should go back to beginning and repeat as it's supposed to.
I ran the code step by step on Visual Studio and it shows that code does not even go through while condition. (no matter what the input value is)
Can someone please help me?
Many thanks in advance!
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))==-1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
return inputCharacters;
} while (invalidCharacters != null);
}
}
}
The problem is that you return the inputed string at the end of the loop no matter the validation done.
You can use a boolean to check this validity.
Also you don't need to parse all the string and you can break the inner loop on the first invalid char.
I renamed the string as result to use a standard pattern and to be more clean.
For example:
static string GetUserString(string letters)
{
string result;
bool isValid;
do
{
Console.Write("Enter : ");
result = Console.ReadLine();
isValid = true;
foreach ( char c in result )
if ( letters.IndexOf(char.ToUpper(c)) == -1 )
{
isValid = false;
Console.WriteLine("Enter a valid input");
break;
}
}
while ( !isValid );
return result;
}
The line return inputCharacters; makes it leave the loop.
I think you meant:
} while (invalidCharacters != null);
return inputCharacters;
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))== -1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
} while (invalidCharacters != null);
return inputCharacters;
}
}
}
I am trying to create 7 BOOM game. if you don't know the rules, everyone takes turns and says the next number but if the number can be divided by seven or contain seven you should say BOOM instead. so in my version, you insert a number and the program should show you all the numbers to that point.
So here is my problem, I succeeded in implementing the first part but I am having a problem with the second one. This is what I have until now:
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = 0;
bool boolean;
while (num1>num2)
{
num2++;
if (num2%7 == 0)
{
Console.Write("BOOM, ");
}
else
{
Console.Write(num2 + ", ");
}
}
}
}
Just change your validation to:
if (num2%7 == 0 || num2.ToString().IndexOf('7') != -1)
{
// (..)
}
The IndexOf function looks for and returns the position of a substring in a string. If it is not found, it returns -1.
As pointed by #Dimitry, another option is
if (num2%7 == 0 || num2.ToString().Contains('7'))
{
// (..)
}
This uses the extension method Contains that returns true or false if the substring exists on the string.
public static void Main()
{
Console.Write("Please enter a number: ");
int number = int.Parse(Console.ReadLine());
// validate number here....
for (int i = 1; i <= number; i++)
{
string value = IsMultipleOrContains7(i) ? "BOOM" : i.ToString();
Console.WriteLine(value);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static bool IsMultipleOrContains7(int number)
{
if (number % 7 == 0)
{
return true;
}
return number.ToString().Contains("7");
}
In my hangman game, I am attempting to prompt the user to enter the number of "lives" (or guesses) the player should be given. After I type a number at the prompt, the following error message is displayed:
Cannot implicitly convert type 'int' to 'string'
The following line causes the error:
lives = Console.ReadLine();
The lives field is an integer. How can I correctly assign a user-entered value to an integer field?
Here is my complete code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Hangman
{
//guesses
public static int lives = 5;
//Words for the game
static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
// Create new ArrayList and initialize with words from array wordBank
static ArrayList wordList = new ArrayList(wordBank);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "C# Hangman";
Console.WriteLine("Hang man!");
//Gamemenu
string response = "";
do
{
Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
response = Console.ReadLine();
switch (response)
{
case "1": AddWord(); break;
case "2": ListWords(); break;
case "3": Play(); break;
case "4": break;
}
} while (response != "4");
}
//add words to list
static void AddWord()
{
Console.Write("Enter the word to add: ");
String temp = Console.ReadLine();
wordList.Add(temp);
Console.WriteLine("{0} was added to the dictionary!", temp);
}
//Display words
static void ListWords()
{
foreach (Object obj in wordList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
//How many guesses
static void AskLives()
{
try
{
Console.WriteLine("please enter number of lives?");
//This line gives me the error
lives = Console.ReadLine();
}
catch
{
// if user does not enter a number ask it again
AskLives();
}
}
//Gameplay
static void Play()
{
Random random = new Random((int)DateTime.Now.Ticks);
string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
string wordToGuessUppercase = wordToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
displayToPlayer.Append('-');
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
bool won = false;
int lettersRevealed = 0;
string input;
char guess;
AskLives();
while (!won && lives > 0)
{
Console.WriteLine("Current word: " + displayToPlayer);
Console.Write("Guess a letter: ");
input = Console.ReadLine().ToUpper();
guess = input[0];
if (correctGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
continue;
}
else if (incorrectGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
continue;
}
if (wordToGuessUppercase.Contains(guess))
{
correctGuesses.Add(guess);
for (int i = 0; i < wordToGuess.Length; i++)
{
if (wordToGuessUppercase[i] == guess)
{
displayToPlayer[i] = wordToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == wordToGuess.Length)
won = true;
}
else
{
incorrectGuesses.Add(guess);
Console.WriteLine("Nope, there's no '{0}' in it!", guess);
lives--;
}
Console.WriteLine(displayToPlayer.ToString());
}
if (won)
Console.WriteLine("You won!");
else
Console.WriteLine("You lost! It was '{0}'", wordToGuess);
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Your lives field is an integer, but Console.ReadLine returns a string.
You can use Int32.Parse(Console.ReadLine()) to parse the input into an integer. Note that an exception will be thrown if the text entered by the user cannot be interpreted as an integer.
Your catch block will work here and re-prompt. It would be more appropriate to use the Int32.TryParse method:
int tmpLives;
if (Int32.TryParse(Console.ReadLine(), out tmpLives))
{
lives = tmpLives;
}
else
{
AskLives();
}
You want to do something along the lines of:
string livesString = Console.ReadLine();
lives = Convert.ToInt32(livesString);
I'm guessing Console.ReadLine() gives you a string. This will not play ball with your integer lives. You could try this:
lives = Int.Parse(Console.ReadLine())