Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I'm trying to make a simple calculator in C# but I'm getting some errors.
Here's my code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculator_c_sharp
{
class Program
{
static void Main(string[] args)
{
//Calculator inputs
Console.WriteLine("Enter the first integer.");
int int1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second integer.");
int int2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter operation.");
string oper = Console.ReadLine();
//Calculator solving
if (oper == "+") ;
{
int ans = int1 + int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "-") ;
{
int ans = int1 - int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "*");
{
int ans = int1 * int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "/") ;
{
int ans = int1 / int2;
Console.WriteLine("Answer = " + ans);
}
else
{
Console.WriteLine("Error.");
}
}
}
}
Visual Studio is saying there's an error at the bottom } after every if statement.
Could someone please tell me what I'm doing wrong here?
No semicolon after if else or other keywords of the nature.
if (oper == "+")
{
int ans = int1 + int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "-")
{
int ans = int1 - int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "*")
{
int ans = int1 * int2;
Console.WriteLine("Answer = " + ans);
}
else if (oper == "/")
{
int ans = int1 / int2;
Console.WriteLine("Answer = " + ans);
}
else
{
Console.WriteLine("Error.");
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
using System;
using System.Data;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
bool calc1 = false;
bool end = false;
double answer = 0.0;
double num1 = Convert.ToDouble(Console.ReadLine());
string op1 = Console.ReadLine();
double num2 = Convert.ToDouble(Console.ReadLine());
if (op1 == "*") ;
{
answer = (num1 * num2);
calc1 = true;
}
if (op1 == "/") ;
{
answer = (num1 / num2);
calc1 = true;
}
if (op1 == "+") ;
{
answer = (num1 + num2);
calc1 = true;
}
if (op1 == "-") ;
{
answer = (num1 - num2);
calc1 = true;
}
while (end == false) ;
{
string op2 = Console.ReadLine();
if (op2 == "*") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer * num3);
}
if (op2 == "/") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer / num3);
}
if (op2 == "+") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer + num3);
}
if (op2 == "-") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer - num3);
}
if (op2 == "=") ;
{
Console.WriteLine(answer);
end = true;
}
}
}
}
}
I am trying to create a multi integer calculator but for some reason, my while loop does not execute so once I enter the first 2 digits and operator, it stops running. Before hand, I had 2 while loops and it would run the second one but it would not print the answer variable when the user entered =.
your issue is the semicolon ; after the while condition.
Remove it. (and also all the ; after the if conditions!)
Currently the code is like that:
while (condition);
{ you big block of code } // <--- this is not part of the while loop
Because of the semicolon, it's actually the same as
while (condition)
;
the big block of code // <--- this is not part of the while loop
or even:
while (condition)
{
}
the big block of code // <--- this is not part of the while loop
If you remove the semicolon, then the block is now part of the loop;
while (condition)
{
the big block of code // <--- Now it's like you intended to write!
}
This is the same problem with the ifs, by the way.
If you write a if (condition);, that's like if (condition) { }, and the other block below will be always executed.
You put a semicolon after the while loop, nothing is inside of it.
If you want to have a forever loop, I suggest you use while(true)
Edit:
OP, If you wanted to exit the loop at any time, you could simply just do break; instead of setting the condition equal to false.
This question already has answers here:
How to replace multiple if statements i to more compact code/class in C#?
(5 answers)
Closed last year.
I'm baby-new to c# and building a project on mental health with multiple objects - starting with loops. Is there more tactful way to approach this code?
I ran basic code input via following:
Console.WriteLine("How are you feeling (1-bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (! Int32.TryParse(userInput, out x))
{
Console.WriteLine("Invalid data input");
}
else if (x == 1)
{
Console.WriteLine(" very low.");
}
else if (x == 2)
{
Console.WriteLine(" low.");
}
else if (x == 3)
{
Console.WriteLine(" average.");
}
else if (x == 4)
{
Console.WriteLine(" good.");
}
else if (x == 5)
{
Console.WriteLine(" very good.");
}
try this, it is more compact code
var invalidData = false;
var x = 0;
var moods = new string[] { " very low.", " low.", " average.", " good.", " very good." };
do
{
Console.WriteLine("How are you feeling(1 - bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (!Int32.TryParse(userInput, out x) || x < 1 || x > 5)
{
Console.WriteLine("Invalid data input");
invalidData = true;
}
else invalidData = false;
}
while (invalidData);
Console.WriteLine(moods[x-1]);
I'm working on making a running total for a coin calculator we're creating for a school project. It's a C# program running in Visual Studio 2019. Currently, I have it adding total change for a single instance, but I need to add a running total that shows before you end the program.
I've tried looking online, but I cant seem to find code that would fit into what I am making. I'm a beginner with C#, so all my ideas have fallen short. Here is my code; hopefully someone can help me out. (Note that the running total should go into the while statement when the user enters N.)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
Well just keep a variable that will sum all iterations
For example:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
int grandTotal = 0;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
// once the user puts his change add the total cents to the grandtotal
// variable
grandTotal += totcents;
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
// here print the value
Console.WriteLine($"You have a total of {grandTotal / 100} dollars and {grandTotal % 100} cents");
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
I added some comments in the code for more clarity
Hope this helps
I am new here so please excuse me for the poor formatting,
I wrote a simple calculator in c# but it seems my multiplication and division are not working correctly.
when running the code it works fine until I try to output the answer and then it outputs "Error, Unknown operator" which is what I told it to output when it doesn't identify the operator stored in the operation variable.
here is the code (sorry for dumping so much code, I am not sure what is relevant and what is not):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class MainClass
{
public static void Main(string[] args) // method called "main", when the program starts, this runs
{
start:
// variable declarations
double Num1;
double Num2;
int operationId;
string operationName = "1";
string operationName2 = "1";
Char operation;
double answer;
// choosing an operator
Console.WriteLine("select an operation from the list and type it's associated number:");
Console.WriteLine("1 - sum \n" + "2 - subtraction \n" + "3 - division\n" + "4 - multipication \n");
operationId = Convert.ToInt32(Console.ReadLine());
// checking which operation has been chosen
if (operationId == 1)
{
operationName = "added to";
operationName2 = "added";
operation = '+';
} else if (operationId == 2)
{
operationName = "subtracted from";
operationName2 = "subtracted";
operation = '-';
} else if (operationId == 3)
{
operationName = "divided";
operationName2 = "divided by";
operation = '/';
} else if (operationId == 4)
{
operationName = "multiplied";
operationName2 = "multiplied by";
operation = '*';
} else
{
Console.WriteLine("Invalid option");
goto start;
}
// receving user input
Console.WriteLine("Insert a number to be " + operationName + ":");
Num1 = Convert.ToDouble (Console.ReadLine());
Console.WriteLine("Insert a number to be " + operationName2);
Num2 = Convert.ToDouble(Console.ReadLine());
//calculating answer
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}
Console.WriteLine();
Console.WriteLine("The result is:");
Console.WriteLine(answer);
Console.ReadKey();
Console.WriteLine();
goto start;
}
}
}
Your first 2 ifs check operation, the second 2 check operationId. Change the multiply and divide ones to also check operation.
//...
else if (operation == '/')
{
answer = Num1 / Num2;
}
else if (operation == '*')
{
answer = Num1 * Num2; //<-- Change to this from Num1 + Num2
}
//...
And by the way, your multiply block is adding the numbers, not multiplying. I've fixed that in my block above.
I guess the problem is with - 2 conditions are checking operation and 2 conditions are checking operationId. Perhaps you may want to change all the checks to be either with operation or with operationId.
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}
Okay, I am using an Automobile class that I have created myself. I am trying to use a List<Automobile>. I am trying to write this program that will use the List<Automobile> and storing the users input in my Automobile class. When I run my code and try to put more than one car in my List<Automobile>, it just overwrites the previous car that the user entered. I know that my code is a mess. I am completely new to using List<> and writing/reading files.
Just in case I was not very clear in my ramblings. I am trying to figure out why my List<Automobile> keeps getting over written when more than one car is wrote to the List<Automobile>.
Thank you in advance to anyone and everyone's help with me solving this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Exercise6_DealerVehicleInventory
{
class Program
{
static void Main(string[] args)
{
#region Variables/Constructors
var answer = "";
Automobile car = new Automobile();
List<Automobile> vehicle = new List<Automobile>();
#endregion
#region User Car Input
/* I might be able to put all of this in one big while loop that way I
* can have more than one vehicle wrote to this file at a time. */
Console.Write("Do you want to add a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
while (answer == "Y" || answer == "y")
{
Console.Write("\nEnter the make of the car: ");
car.Make = Console.ReadLine();
Console.Write("Enter the model of the car: ");
car.Model = Console.ReadLine();
Console.Write("Enter the color of the car: ");
car.Color = Console.ReadLine();
Console.Write("Enter the year of the car: ");
car.Year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the mileage of the car: ");
car.Mileage = Convert.ToInt32(Console.ReadLine());
vehicle.Add(car);
Console.Write("Do you want to add a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
}
#endregion
#region Delete From In Memory
Console.Write("\nDo you want to delete a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
int i = 0;
int delEntry = 0;
foreach(Automobile automobile in vehicle)
{
Console.Write("#" + i + " = " + automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage + "\n");
i++;
}
Console.WriteLine("\nWhat item number would you like to delete: ");
delEntry = Convert.ToInt32(Console.ReadLine());
vehicle.RemoveAt(delEntry);
}
#endregion
#region Write Data To File
Console.Write("\nDo you want to write this to a text file?\nY for yes or N for no: ");
answer = Console.ReadLine();
string mydocpath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (answer == "Y" || answer == "y") //(string.Equals("y", answer, StringComparison.CurrentCultureIgnoreCase))
{
using (StreamWriter sw = new StreamWriter(mydocpath + #"\Vehicle.txt"))
{
foreach (Automobile automobile in vehicle)
{
sw.WriteLine(automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage);
}
}
}
else
{
Console.WriteLine("No data wrote to file: ");
}
#endregion
#region Update Vehicle File
Console.Write("\nWould you like to add another vehicle?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
StreamReader sr = new StreamReader(mydocpath + #"\Vehicle.txt");
String line = sr.ReadLine();
Console.Write("\n" + line);
while (answer == "Y" || answer == "y")
{
Console.Write("Enter the make of the car: ");
car.Make = Console.ReadLine();
Console.Write("Enter the model of the car: ");
car.Model = Console.ReadLine();
Console.Write("Enter the color of the car: ");
car.Color = Console.ReadLine();
Console.Write("Enter the year of the car: ");
car.Year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the mileage of the car: ");
car.Mileage = Convert.ToInt32(Console.ReadLine());
vehicle.Add(car);
Console.Write("\nDo you want to delete a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
int i = 0;
int delEntry = 0;
foreach (Automobile automobile in vehicle)
{
Console.Write("#" + i + " = " + automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage + "\n");
i++;
}
Console.WriteLine("\nWhat item number would you like to delete: ");
delEntry = Convert.ToInt32(Console.ReadLine());
vehicle.RemoveAt(delEntry);
}
Console.Write("\nDo you want to write this to a text file?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y") //(string.Equals("y", answer, StringComparison.CurrentCultureIgnoreCase))
{
using (StreamWriter sw = new StreamWriter(mydocpath + #"\Vehicle.txt", true))
{
foreach (Automobile automobile in vehicle)
{
sw.WriteLine(automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage);
}
}
}
}
}
else
{
Console.WriteLine("Nothing else was added to the file.");
}
#endregion
Console.ReadLine();
}
}
}
Below is my Automobile class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise6_DealerVehicleInventory
{
class Automobile
{
private string _make;
public string Make
{
get { return _make; }
set { _make = value; }
}
private string _model;
public string Model
{
get { return _model; }
set { _model = value; }
}
private string _color;
public string Color
{
get { return _color; }
set { _color = value; }
}
private int _year;
public int Year
{
get { return _year; }
set { _year = value; }
}
private int _mileage;
public int Mileage
{
get { return _mileage; }
set { _mileage = value; }
}
}
}
You need to instantiate a new Automobile each time you iterate the while loop, otherwise you're just operating on the same instance and overwriting it.
Move this line:
Automobile car = new Automobile();
To here:
while (answer == "Y" || answer == "y")
{
Automobile car = new Automobile(); // create a new Automobile each time
Console.Write("\nEnter the make of the car: ");
car.Make = Console.ReadLine();
it may seem like the Automobile object within the list is getting overridden but you're actually adding the same object more than once and just overwriting it's attributes each time.
you'll need to insert this line Automobile car = new Automobile(); within the while loop in order to make a new object independent of the previous Automobile object.
while (answer == "Y" || answer == "y")
{
Automobile car = new Automobile();
...
...
...