Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Its my code :
if (numavg <=3 ){
Console.WriteLine("Congratz, we can start! but some note before :");
Console.WriteLine("When you put the last number, type 'c' in the next line for calculate the avg");
Console.WriteLine("So lets start! type the first number.");
avg1 = int.Parse(Console.ReadLine());
Console.WriteLine("Ok, so you choose " + avg1 + ",who is the next number?");
avg2 = int.Parse(Console.ReadLine());
Console.WriteLine("Wonderful! put the next number");
avg3 = int.Parse(Console.ReadLine());
if (avg3 = "c"){
Console.WriteLine("Ok, Lets calculate!");
average = (avg1 + avg2)/numavg;
Console.WriteLine("The average is " + average + ".");
}
else {
Console.WriteLine("Perfect! please type the next number,or 'c' for avg to the last 3 numbers.");
avg4 = int.Parse(Console.ReadLine());
if (avg4 = "c" ){
Console.WriteLine("Ok, Lets calculate!");
average1 = (avg1 + avg2 + avg3)/numavg;
Console.WriteLine("The average is " + average1 + ".");
}
}
The problem is with type "c" (for calculate the avg).
I dont understand how I can keep avg3 and avg4 as string and int together.
help?
and more pure question -
If I want the program end and restart automaticlly, which code I need type?
(if the restart isn't possible, how can I do the first thing with the auto program closing?)
Thank u guys!
NOTE :
The error is " Cannot implicitly convert type 'string' to 'int'".
do you mean if(avg3 == "c") instead of if (avg3 = "c")
(avg3 = "c") you are assigning "c" to avg3 which is of type int which explains " Cannot implicitly convert type 'string' to 'int'".
String avg3Str = Console.ReadLine();
if (avg3Str.equals("c")){
Console.WriteLine("Ok, Lets calculate!");
average = (avg1 + avg2)/numavg;
Console.WriteLine("The average is " + average + ".");
}
else {
avg3 = int.Parse(avg3Str);
Console.WriteLine("Perfect! please type the next number,or 'c' for avg to the last 3 numbers.");
String avg4Str = Console.ReadLine();
if (avg4Str.equals("c") ){
Console.WriteLine("Ok, Lets calculate!");
average1 = (avg1 + avg2 + avg3)/numavg;
Console.WriteLine("The average is " + average1 + ".");
}
else
{
avg4 = int.Parse(avg4Str);
Console.WriteLine("Ok, Lets calculate!");
average1 = (avg1 + avg2 + avg3 + avg4)/numavg;
Console.WriteLine("The average is " + average1 + ".");
}
}
Related
This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
How can I divide two integers to get a double?
(9 answers)
Closed 4 months ago.
I am new to coding in general, and especially new to C#. I am trying to write a program that asks the user if they want to convert a temperature to Fahrenheit or Celsius. The issue is, the math isn't checking out
This is what I have so far, and from what I know, it should work:
//declare variables
double temp = 0;
double newTemp = 0;
string? cf = "";
//ask if they want to covert to celcius or farenheit
Console.WriteLine("What are you converting to? Enter c for celsius or f for farenheit:");
cf = Console.ReadLine();
//if statement and output
if(cf == "c")
{
Console.WriteLine("Converting to Celsius. Enter temperature in farenheit:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp - 32) * (5/9);
Console.WriteLine("Your temperature in celcius is " + newTemp + " degrees celsius.");
}
else if(cf == "C")
{
Console.WriteLine("Converting to Celsius. Enter temperature in farenheit:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = ((temp - 32) * (5/9));
Console.WriteLine("Your temperature in celcius is " + newTemp + " degrees celsius.");
}
else if(cf == "f")
{
Console.WriteLine("Converting to Farenheit. Enter temperature in celsius:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp * (9/5) + 32);
Console.WriteLine("Your temperature in farenheit is " + newTemp + " degrees farenheit.");
}
else if(cf == "F")
{
Console.WriteLine("Converting to Farenheit. Enter temperature in celsius:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp * (9/5) + 32);
Console.WriteLine("Your temperature in farenheit is " + newTemp + " degrees farenheit.");
}
else
{
Console.WriteLine("That is not celcius or farenheit. Please enter either c or f next time.");
Environment.Exit(0);
}
For some reason that I cant figure out, the math is always wrong. -40 degrees is never equal to -40 degrees in the inverse temperature, meaning that the math is incorrect. Would anyone be able to explain to me, in beginners terms, what the issue is and how I might resolve it?
P.S. - in many forums I looked at first, they used a term called floating-point that I don't really understand. If you use this in your answer, I would really appreciate an explanation on what it means.
Calculation the division 9/5 will treat both values as integer. This means the result is another integer which is 1 in this case.
To ensure the calculation is done like expected at least on of the numbers needs to be a double like 9.0/5. This results in the expected value of 1.8.
See this question for more details about this.
Another hint: You do not need to copy the whole code for lower and upper case input like
if (cf == "f")
{
//Code
}
else if (cf == "F")
{
//The same code
}
Just simply could make use of the or operator like
if (cf == "f" || cf == "F")
or use to lower
if (cf.ToLower() == "f")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm new.
my problem:
class Battle
{
public void Fight(string charOne, string charTwo)
{
void CurrentHealth()
{
Console.WriteLine(charOne.name + "'s Health: " +
charOne.currentHealth + "/" + charOne.maxHealth +
" | " + charTwo.name + "'s Health: " + charTwo.currentHealth +
"/" + charTwo.maxHealth);
}
}
}
the ".name" and ".currentHealth" are not working.
charOne would be a class instance, and charTwo would be another class instance.
[UPDATE BELOW]
Below was the code that was originally working in the main program class, and I was trying to move it in to a class, where I could pass in some parameters to the class, so the Hero could fight other monsters in the future. This single time monster was "mosquito".
I just want to be able to replace a "mosquito" with a "wolf" class and maybe "hero2" instead of "hero". Hope this makes more sense.
void CurrentHealth()
{
Console.WriteLine(hero.name + "'s Health: " + hero.currentHealth + "/" + hero.maxHealth + " | " + mosquito.name + "'s Health: " + mosquito.currentHealth + "/" + mosquito.maxHealth);
}
void Attack(int dmg)
{
Console.WriteLine(hero.name + " Dealt " + dmg + " damage to " + mosquito.name + ".");
}
while (mosquito.currentHealth > 0 && hero.currentHealth > 0)
{
Console.Clear();
int damage = hero.AttackAction();
mosquito.currentHealth = mosquito.currentHealth - damage;
int newHealth = mosquito.currentHealth;
Attack(damage);
CurrentHealth();
Console.WriteLine();
Console.WriteLine("Press any key to continue.");
Console.Read();
}
if (mosquito.currentHealth <= 0)
{
Console.WriteLine("Right on! You are Victorious!!!");
}
else if (hero.currentHealth <= 0)
{
Console.WriteLine("Oh no.. you are dead...");
}
else
{
Console.WriteLine("You reached the end.");
}
public void Fight(MyCharacterClass charOne, MyCharacterClass charTwo)
Try it like this, of course change your own class with MyCharacterClass
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.
using System;
class CalculatorProgram
{
//varibale for do-while loop
private static string endAnswer;
public static void Main() // <----- The Entry point
{
//Variables
string Choice1;
string mathChoice;
decimal Num1;
decimal Num2;
decimal Answer;
bool userWrong = true;
Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
Choice1 = Console.ReadLine();
while(userWrong)
{
if (Choice1 == "Yes")
{
do
{
Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
//User inputs the 2 numbers
//Math Choices
if (mathChoice == "Add")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 + Num2;
Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
}
else if (mathChoice == "Subtract")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 - Num2;
Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
}
else if (mathChoice == "Multiply")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 * Num2;
Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
}
else if (mathChoice == "Divide")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 / Num2;
Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
}
else
{
Console.WriteLine("This is not an option! Shutting Down..");
Console.ReadKey();
Environment.Exit(0);
}
//varibale for while loop to continue if selected Yes.
Console.Write("Another Equation?: ");
endAnswer = Console.ReadLine();
} while (endAnswer == "Yes");
//Goodbye Message
Console.WriteLine("Thank you for using my program, goodbye ");
Console.ReadKey();
Environment.Exit(0);
userWrong = false;
}
//If someone selects no for wanting to use my program.
else if (Choice1 == "No")
{
Console.WriteLine("Thank you for using my program, goodbye ");
Console.ReadKey();
Environment.Exit(0);
}
else
{
Console.WriteLine("That is not an option");
Console.ReadLine();
}
}
}
}
The program is waiting for the user to input a new answer after it prints out "That is not an option," you just never prompt them for it. You also never store Choice1 again based on their new input, so it will always check the first if condition in your do-while loop with whatever they initially put in.
To fix it, change your else branch body to something like this.
//...
else
{
Console.WriteLine("That is not an option");
// reprompt the user so they know to type something in
Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
// store the new choice to recheck next loop iteration
Choice1 = Console.ReadLine();
}
Probably your problem is that you don’t make a correct validation of the input.
Now, you read the input from console and compare with a static string so
“Add” is different from “add” and different from “Add(space)“.
I suggest you to make a more strong input validation:
Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
mathChoice = mathChoice.ToUpper().Trim();
//User inputs the 2 numbers
//Math Choices
if (mathChoice == "ADD")
{
Console.WriteLine("What 2 numbers would you like to use?");
....
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm 100% new to programming, this is what I want:
(Name) No numbers
(Card Number) Limit to 16 digits and no letters
(Expiry Date) Numbers like this - "02/17" and no letters
(Security Code) Limit to 3 numbers and no letters.
My code:
string message =
"Name: " + nameTextBox.Text +
"\nCard Number: " + cardNumberTextBox.Text +
"\nExpiry Date: " + expiryDateTextBox.Text +
"\nSecurity Code: " + securityCodeTextBox.Text +
"\nOrder: Pizza " + pizzaType + ", " + pizzaSize;
if (TotalToppingQuantities() > 0)
{
for (int toppingIndex = 0; toppingIndex < toppingQuantities.Length; toppingIndex++)
{
if (toppingQuantities[toppingIndex] > 0)
{
message += ", " + toppingQuantities[toppingIndex] + " x " +
toppingNames[toppingIndex];
}
}
}
message +=
"\nPickup Spot: " + pickupSpot +
"\nDelivery Time: 30 minutes";
MessageBox.Show(message);
For your problem, regex is good solution.
And this should work for you
using System.Text.RegularExpressions;
//====================================
if (Regex.Match(nameTextBox.Text, "\\d").Success)
{
MessageBox.Show("(Name) must contain No numbers");
return ;
}
if (!Regex.Match(cardNumberTextBox.Text, "^\\d{16}$").Success)
{
MessageBox.Show("(Card Number) must be Limited to 16 digits and no letters");
return ;
}
if (!Regex.Match(expiryDateTextBox.Text, "^\\d{2}/\\d{2}$").Success)
{
MessageBox.Show("(Expiry Date) must be Numbers like this - 02/17 and no letters");
return ;
}
if (!Regex.Match(securityCodeTextBox.Text, "^\\d{3}$").Success)
{
MessageBox.Show("(Security Code) must be Limited to 3 numbers and no letters.");
return ;
}
I am new to programming and am attempting to learn c#. I am having what i think is a simple problem with my console application(the code is below). The error appears to be with my if statement which reads as follows:
//evaluate subtotals to results
if (subTotalOne == subTotalTwo)
{
Console.WriteLine("=");
}
else if (subTotalOne < subTotalTwo)
{
Console.WriteLine("<");
}
else (subTotalOne > subTotalTwo);
{
Console.WriteLine(">");
}
The error i get is: Only assignment, call, increment, decrement, and new object expressions can be used as a statement.
Any help would be appreciated. I have read through the forums here and seen may similar questions but my understanding isn't good enough yet to map the solutions i've seen to my problem.
Full application code:
using System;
namespace itc110_a02_GroceryComparison
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Compare Grocery Stores "); //Alert user to purpose of program with title
Console.WriteLine("\n");//line break
// Store 1
Console.WriteLine("Enter the name of the first store for comparison: ");//storeName 1
String storeOne = Console.ReadLine();//ToLower for eval
//store 1, first item
Console.WriteLine("Name of First product purchased at " + storeOne + ": ");//ask item
String purchaseOne = Console.ReadLine();//collect item
Console.WriteLine("Price paid for first purchased at " + storeOne + ": ");//ask 1st price
Double price1A = Double.Parse(Console.ReadLine());//collect 1st price
//store 1, second item, repeat process -- this ought to be a method or a function
Console.WriteLine("Name of second product purchased at " + storeOne + ": ");//ask item
String purchaseTwo = Console.ReadLine();//collect Item
Console.WriteLine("Price paid for second purchased at " + storeOne + ": ");//Ask Item Price
Double price1B = Double.Parse(Console.ReadLine());//Collect Item Price
Console.WriteLine("\n");
// Store 2, repeat process -- this ought to be a method or a function
Console.WriteLine("Enter the name of the second store for comparison: ");//Store name 1
String storeTwo = Console.ReadLine();// To Evals entry, we ToLower to set to lower case
//store 2
Console.WriteLine("Price paid for " + purchaseOne + " at " + storeTwo + ": ");//ask 1st price
Double price2A = Double.Parse(Console.ReadLine());//collect 1st price
//store 2, second item
Console.WriteLine("Price paid for " + purchaseTwo + " at " + storeTwo + ": ");//Ask Item Price
Double price2B = Double.Parse(Console.ReadLine());//Collect Item Price
Console.WriteLine("\n");
// Results go here
//Store one totals
Console.WriteLine("************ " + storeOne + " ************");
Console.WriteLine(purchaseOne + ": $" + price1A);
Console.WriteLine(purchaseTwo + ": $" + price1B);
Console.WriteLine("\n \n");
// store two totals
Console.WriteLine("************ " + storeTwo + " ************");
// Result A: Where to shop
Console.WriteLine(purchaseOne + ": $" + price2A);
Console.WriteLine(purchaseTwo + ": $" + price2B);
Console.WriteLine("\n \n");
Console.WriteLine("************ After Price Comparison ************");
//merge subtotals
Double subTotalOne = (price1A + price1B);
Double subTotalTwo = (price2A + price2B);
//evaluate subtotals to results
if (subTotalOne == subTotalTwo)
{
Console.WriteLine("=");
}
else if (subTotalOne < subTotalTwo)
{
Console.WriteLine("<");
}
else (subTotalOne > subTotalTwo);
{
Console.WriteLine(">");
}
//keeps the console open
Console.Read();
}
}
}
This else line is the problem.
else (subTotalOne > subTotalTwo);
{
Console.WriteLine(">");
}
Fixed:
else
{
Console.WriteLine(">");
}
Explanation:
Your code is equivalent to:
else
(subTotalOne > subTotalTwo);//else block
{
Console.WriteLine(">");
}
semicolon makes the condition expression as statement and so the error.
However, the next console statement will also not be part of else block as the else block finishes after semicolon. So, even if the condition expression was a valid statement, ">" will always be printed which is not desired.
You are probably going for:
else
{
Console.WriteLine(">");
}
since you have eliminated all other possibilities.
On a formatting front I have never been a fan of else if all one line. For beginners especially, it can obscure program flow. There are others who completely disagree with me though...