Single line calculator - problem with last number [duplicate] - c#

This question already has answers here:
Evaluating string "3*(4+2)" yield int 18 [duplicate]
(13 answers)
Closed 3 years ago.
I created a console application that will take user input of any number and + or - operator for now, and returns the result.
for example user can input 1+2+3+4, and result should be 10.
My problem is that I cannot figure out how to get the last number to be summed into the total result.
that mean in my code only 1+2+3 will be calculated while 4 will be ignored.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCalculator
{
public class Program
{
public static void Main()
{
int result = 0;
int number;
string numberString = "";
Console.WriteLine("Enter numbers followed by operation eg. x+y-z");
while (true)
{
string userInput = UserInput();
//Loop into each element of the input string
for (int i = 0; i < userInput.Length; i++)
{
if((IsNumber(userInput[i])))
{
numberString += userInput[i];
}
else if (!IsNumber(userInput[i]))
{
number = Int32.Parse(numberString);
numberString = "";
result = PerformCalculation(result, number, userInput[i]);
}
}
number = Int32.Parse(numberString);
result += number;
Console.WriteLine($"{userInput}={result}");
}
}
// check if input is number or operator
static bool IsNumber(char input)
{
if (char.IsDigit(input)){return true;}
else{return false;}
}
static string UserInput()
{
string User_input = Console.ReadLine();
return User_input;
}
static int PerformCalculation(int sum, int num, char op)
{
switch (op)
{
case '+': return sum + num;
case '-': return sum - num;
default: throw new ArgumentException("Uknown operator");
}
}
}
}

You have already figured out that you are not adding the last number and lets do some thinking to figure out why.
The number will only be added when you call PerformCalculation and whats the condition that this will be called? else if (!IsNumber(userInput[i]))
If you look at your input do you see a non number at the end of the string? if not then PerformCalculation wont get called.
How do you fix that? Before you return the result check if numberString is empty, if not then do the final calculation before returning the result.
Since this is a homework problem i will leave the rest as an exercise.

Related

How Can I sum all digits in a number using loop?

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?

How do I check if the calculator is only accepting numbers? [duplicate]

This question already has answers here:
C# Input string was not in a correct format
(4 answers)
How the int.TryParse actually works
(6 answers)
Closed 2 years ago.
I am making a console calculator. Currently I am stuck at this check. Essentially, after I ask the user for a number, I want to make a conditional statement where when they press anything else I want to give them a message.
How would I do this? I was thinking if there was any way I can check between the datatypes and compare them in an if statements.
static void Main(string[] args)
{
Console.Write("What sort of calculation do you want to perform? (+,-,*, or /) ");
string operato= Console.ReadLine();
Console.Write("Choose a number..");
int numeroUno = Convert.ToInt32(Console.ReadLine());
if (numeroUno);
Console.Write("Choose another number ");
int numeroDos = Convert.ToInt32(Console.ReadLine());
Calculator calculator = new Calculator();
calculator.a = numeroUno;
calculator.b = numeroDos;
calculator.Add(numeroUno, numeroDos);
calculator.subtract(numeroUno, numeroDos);
calculator.Multiplication(numeroUno, numeroDos);
calculator.Division(numeroUno, numeroDos);
if (operato == "+")
{
Console.WriteLine(calculator.Add(numeroUno, numeroDos));
}
else if (operato == "-")
{
Console.WriteLine(calculator.Add(numeroUno, numeroDos));
}
else if (operato == "*")
{
Console.WriteLine(calculator.Multiplication(numeroUno, numeroDos));
}
else if (operato == "/")
{
Console.WriteLine(calculator.Division(numeroUno, numeroDos));
}
else
{
Console.WriteLine(" Pick on of the four options idiot");
}
Console.ReadLine();
}
I can advise you to use Try parse
https://learn.microsoft.com/it-it/dotnet/api/system.int32.tryparse?view=netcore-3.1
with this you can check if the typed character is a number.
Example:
public class Example
{
public static void Main ()
{
String [] values ​​= {null, "160519", "9432.0", "16,667",
"-322", "+4302", "(100);", "01FA"};
foreach (var value in values)
{
int number;
bool success = Int32.TryParse (value, out number);
if (success)
{
Console.WriteLine ("Converted '{0}' to {1}.", Value, number);
}
else
{
Console.WriteLine ("Attempted conversion of '{0}' failed.",
value ?? "<Null>");
}
}
}
}
If it were not a number I would use a switch case control I find it cleaner

Why is my program requiring two lines of input and why is my GPA calculation wrong c#?

I am making a program to calculate GPA. I have it mostly working, but I can't figure out why it is asking for 2 inputs and why the calculation of GPA is wrong. I also need to make it so that I can input uppercase or lowercase letters. If you can offer a way to rewrite, it would be greatly appreciated.
This is the program:
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace gpa
{
class Program
{
static void Main(string[] args)
{
//create a list for the grades to go into
List<double> GradeList = new List<double>();
Console.Write("\n********************************************\n");
bool LastGrade = false;
while (LastGrade == false)
{
//pass letter as parameter to get the GradePoint
double Grade = Calculations.GetGradePoint();
if (Console.ReadLine() == "")
{
LastGrade = true;
}
else
{
GradeList.Add(Grade);
}
}
//add all the gradepoints and round to 2 decimal places
double TotalGradePoints = Math.Round(GradeList.Sum(), 2);
Console.WriteLine($"your total grade points are {TotalGradePoints}");
Console.WriteLine("How many total credits did you take this semester?");
double TotalCredits = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"total credits {TotalCredits}");
double EndGPA = Calculations.GPA(TotalGradePoints, TotalCredits);
Console.WriteLine($"Your GPA this semester will be {EndGPA}");
}
}
}
This is the calculations class I added:
using System;
namespace gpa
{
public class Calculations
{
public static double GPA(double points, double credits)
{
double average = points / credits;
return average;
}
public static double GetGradePoint()
{
Console.WriteLine("Enter your letter grade for each class");
double Grade = 0;
string letter = Console.ReadLine();
if (letter == "A")
{
return 4;
}
if (letter == "A-")
{
return 3.7;
}
if (letter == "B+")
{
return 3.3;
}
if (letter == "B")
{
return 3;
}
if (letter == "B-")
{
return 2.7;
}
if (letter == "C+")
{
return 2.3;
}
if (letter == "C")
{
return 2;
}
if (letter == "C-")
{
return 1.7;
}
if (letter == "D+")
{
return 1.3;
}
if (letter == "D")
{
return 1;
}
if (letter == "F")
{
return 0;
}
return Grade;
//do not need to add looping mechanism in this fucntion - loop it in the main function
// Write function that takes a letter grade as input
// and returns the grade-point value of that letter grade
// Replace your switch statement above with a call to this function
}
}
}
This is the output:
enter image description here
Your program logic is flawed. So. You have a loop that keeps looping and invokes a method. In this method GetGradePoint you ask for the Grade input and then read the input using Console.ReadLine().
This is fine. The issue comes after. You wait for an input from the user again and if they input anything other than an empty string, the program will add the first input grade value and then loop back around as LastGrade is still false.
This means that the program starts from the start of the loop which means it will then invoke the GetGradePoint method again which is why it asks for the input again. Also if you then enter an empty string, the grade the user input doesn't get added to the GradeList list.
You need to go through your program as the issue, as I said, is the logic of your program. I suspect the other issue of the GPA being wrong will also correct itself.
Code Tips:
Instead of doing 1,000 if statements, as you're only accepting a single character you can use else if for the rest of the statements. Although this doesn't matter a huge lot as you are returning a value. IE:
if(condition)
{
}
else if(other condition)
{
}
Your while loop accepts a Boolean value as the condition which == provides but you can instead use your LastGrade variable as the condition for the loop IE:
while(!LastPass)
{
}
As for getting input I would rewrite it to something like
//Remove the line in GetGradePoint if you're gonna put it here
Console.WriteLine("Enter your grades");
while(condition)
{
string input = Console.ReadLine();
if(input != "")
{
var grade = GetGradePoint(input);
GradeList.Add(grade);
}
else LastGrade = true;
}
//Rest of code to calculate GPA
This is rough pseudo-c# code.
As for accepting both lower and upper case: You can use .ToUpper() on the input to ensure the input is an uppercase letter even if the user enters a lowercase letter.

C# Palindrome Test [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 3 years ago.
I need to create a IsPalindrome function where it will determine if a provided string is a palindrome. Alphanumeric chars will be considered when evaluating whether or not the string is a palindrome. With this said, I am having trouble trying to disreguard the spaces and the Caps. Here is what my function looks like now.
If this makes a difference: After this function is done I will then have to have parse a JSON file and have each element in the "strings" array, into the IsPalindrome function.
Any tips?
private static bool IsPalindrome(string value)
{
var min = 0;
var max = value.Length - 1;
while (true)
{
if (min > max)
return true;
var a = value[min];
var b = value[max];
if (if (char.ToLower(a) == char.ToLower(b))
{
return true;
}
else {
return false;
}
min++;
max--;
}
The way I'd do this is to turn the string into an array of characters, skipping non-letter characters, and making all the characters lowercase. Then, I'd use an index to check if the first half of the array is equal to the last. Something like this:
public static bool IsPalindrome(string value)
{
char[] forwards = (from c in value.ToLower().ToCharArray() where char.IsLetter(c) select c).ToArray();
int middle = (forwards.Length / 2) + 1;
for (int i = 0; i < middle; i++)
if (forwards[i] != forwards[forwards.Length - 1 - i])
return false;
return true;
}
That first line uses LINQ to make the array, so you need a using System.Linq;

c# calculating digit before floating points

I'm trying to calculate the number of digit before the floating points. for example
input: 123.4
expected output: 3
my actual output: 5
I'm sure there is something wrong with the digit.equals(".") since the program does not break out of the loop.
this is my code:
public class Program
{
public static void Main()
{
Console.WriteLine(HowManyDigit(123.4));
}
public static Int32 HowManyDigit(Double number)
{
string x = number.ToString();
var counter = 0;
for (int i = 0; i < x.Length; i++)
{
var digit = x[i];
//Console.WriteLine(counter);
if (digit.Equals("."))
{
break;
}
else
{
counter++;
}
}
return counter;
}
}
The reason your code does not work breaks down to this logic:
var digit = x[i];
if (digit.Equals("."))
{
break;
}
The char digit will never be equal to the string "."
If you change your code to:
//Note that I use a char, indicated by ''
if (x[i].Equals('.'))
{
break;
}
Or simply:
if (x[i] == '.')
{
break;
}
Either of those two methods will give you a drastically different result from your current code.
That being said, this method is not really the best way of doing what you want. You can simply use IndexOf() to get the exact number you want:
public static int HowManyDigit(double number)
{
return number.ToString().IndexOf('.');
}
Fiddle here
Just compute the logarithm of base 10 and then convert to integer with floor.
n = Math.Floor(Math.Log10(x))+1;
Try this x.IndexOf('.') this will be your answer
Replace this:
if (digit.Equals("."))
With this:
if (digit.Equals('.'))
Now your output should be 3.
Here is a LINQ solution:
double number = 123.4;
var result = number.ToString().TakeWhile(x => char.IsDigit(x)).Count();

Categories

Resources