I am new to C# and trying to figure out how to write simple codes to perform basic calculations. I tried to write code for pipe diameter and everything seems to be fine but the result is NaN.
I've tried to change locations for variables declarations as I suspect that there is a problem with. I tried also static keyword but without success.
This is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Pipe_Sizing
//This simple code is intended to calculate diameter of the pipe after getting flow and velcity values from the user
{
class Program {
//This method is created to read input from users and convert it to number
static void readnum(string inp, double num) {
inp = Console.ReadLine();
while ((num = double.Parse(inp)) < 0) {
Console.WriteLine("Sorry, you need value in digits");
inp = Console.ReadLine();
}
Console.WriteLine(num);
}
static string flo;
static double flox;
static string vel;
static double velx;
static void Main()
{
// Get the Flow value from thre user
Console.WriteLine("Please Enter the value of Flow in m3/hr");
readnum(flo, flox);
// Get the Velocity value from the user
Console.WriteLine("Please Enter the value of velcoty in m/s");
readnum(vel, velx);
double dd = (4 * flox) / (3.14 * velx);
double d = Math.Sqrt(dd);
Console.WriteLine("The diameter required for the pipe is " + d);
Console.ReadLine();
}
}
}
How to get the result as a number?
The method readnum does not return anything. The parameters of readnum (inp and num) are local variables to the method - changing their values will have no effect outside the method. Therefore in the Main method the variables flox and velx will still have their default values of 0.0. Change readnum so that it returns the num it parsed from the user input.
Many big No's in your code
static void readnum(string inp, double num)
This is not doing what you think it does (I assume): double is a value Type, meaning it get passed by value and not by reference: you code is going to modify the local (to readnum method) variable. Same for string inp: even if string is a reference type, it works as a value type in this context (for more on this google string c# immutable)
When in Main you call readnum, the variable you are passing are not modified
num = double.Parse(inp)
Parse will throw an exception if the input string is not convertible to a double (same for Parse methods for int, date, etc). You may want to use TryParse and check it return value before proceeding
static double flox;
static double velx;
You actually don't need to have these variables static (nor even class member): just declare them local for the function you are using them: the bigger the scope of a variable, the harder to handle it
static string flo;
static string vel;
Same as above more or less, you actually just need a local variable within readnum
double dd = (4 * flox) / (3.14 * velx);
.Net has a very convenient Math.Pi, much better then a 3.14
This can be a cleaner (and maybe working, not tested) version of your code:
using System;
using System.Text;
public class Program
{
//This method is created to read input from users and convert it to number
static double readnum()
{
string inp = Console.ReadLine();
double res;
while (!double.TryParse(inp, out res)) // add check for negative value
{
Console.WriteLine("Sorry, you need value in digits");
inp = Console.ReadLine();
}
Console.WriteLine(res);
return res;
}
public static void Main()
{
// Get the Flow value from thre user
Console.WriteLine("Please Enter the value of Flow in m3/hr");
double flox = readnum();
// Get the Velocity value from the user
Console.WriteLine("Please Enter the value of velcoty in m/s");
double velx = readnum();
double dd = (4 * flox) / (Math.PI * velx); //
double d = Math.Sqrt(dd);
Console.WriteLine("The diameter required for the pipe is " + d);
Console.ReadLine();
}
}
Related
I have a problem that I have been trying to sort out for quite a while now but I just can't wrap my head around it.
I have two double variables that are initialized. Obviously, I get an error for that because they should have a value. However, the only value I could set it to is 0. The issue with that is, if I set the value to 0, my program does not run correctly and the output of my program becomes 0 too.
Error: Local variable 'userSalary' might not be initialized before accessing
I am still kind of learning the ways of methods, parameters, and arguments.
class Program
{
static void Main(string[] args)
{
double userSalary;
double leftOver;
AskQuestion(userSalary);
CalculateTax(userSalary, leftOver);
}
static void AskQuestion(double userSalary)
{
Console.WriteLine("What is annual your salary?");
userSalary = Convert.ToDouble(Console.ReadLine());
}
static void CalculateTax(double userSalary, double leftOver)
{
if (userSalary <= 14_000) //10%
{
Console.WriteLine("You are in Tax Category 1. 10% of your Salary goes to the state!");
Console.WriteLine("Calculating Salary...");
Thread.Sleep(500);
leftOver = userSalary - (userSalary * 10 / 100);
Console.WriteLine("Your Salary after taxation is: $" + leftOver);
}
}
}
You have multiple problems here.
Firstly, your "Error: Local variable 'userSalary' might not be initialized before accessing" problem:
While fields (class-level variables) are initialized to their default values when constructing a class, method variables are not initialized. To do so, you would need to assign a value to them. For example:
double userSalary = 0;
double leftOver = 0;
The next problem you have is that all variables are passed by value (i.e. a copy is made) and not by reference. Note that this is not to say that the types being passed are not reference types, but that the pointer the variable represents is passed as a copy. You can read more on that here.
What this means for you is that, while AskQuestion changes its own userSalary argument variable, it doesn't change the calling method's variable. One way to solve this is to use the ref or out keywords. (ref is used where the variable is already initialized but the method changes it, out is used where the method initializes the variable). More on that here.
So you could write your code like this:
static void AskQuestion(out double userSalary)
And then call it like so:
double userSalary;
AskQuestion(out userSalary);
or simply:
AskQuestion(out double userSalary);
Though a better approach is to have the method simply return the result. We'll also remove the leftOver argument from CalculateTax as that isn't used anywhere:
Note : You should always use TryParse Style methods to validate user input
static double AskQuestion()
{
double userSalary;
Console.WriteLine("What is annual your salary?");
// simple validation loop
while (!double.TryParse(Console.ReadLine(), out userSalary))
Console.WriteLine("You had one job... What is annual your salary?");
return userSalary;
}
static void CalculateTax(double userSalary)
{
if (userSalary <= 14_000) //10%
{
Console.WriteLine("You are in Tax Category 1. 10% of your Salary goes to the state!");
Console.WriteLine("Calculating Salary...");
Thread.Sleep(500);
double leftOver = userSalary - (userSalary * 10 / 100);
Console.WriteLine("Your Salary after taxation is: $" + leftOver);
}
}
And then initialize userSalary and call CalculateTax like so:
userSalary = AskQuestion();
CalculateTax(userSalary);
Use:
double userSalary=0.0;
double leftOver=0.0;
I have a successful clean code that does a conversion of Celcius to Fahrenheit using Double.Parse. However, I was curious on how it would look if I did a Double.TryParse but I can't seem to figure out how to complete the code. Once executed, I am able to present "Invalid Code", in my "if, else" but I still get this after my Invaild Output...
Please enter a value for conversion:
30x
Invalid code
The conversion from Celcius to Fahrenheit is: 32
using System;
using System.Text;
namespace CSharpBasics
{
class Program
{
public static double CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
}
else
{
Console.WriteLine("Invalid code");
}
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = CelciusToFarenheit(Console.ReadLine());
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + input);
}
}
}
You should verify your input before the conversion to make sure you never display invalid result for an invalid input but return a message notifying the wrong input first. Something like this:
public static double CelciusToFarenheit(double celcius)
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = Console.ReadLine();
double celcius;
if (Double.TryParse(input, out celcius))
{
var result = CelciusToFarenheit(celcius);
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + result);
}
else
{
Console.WriteLine("Invalid code");
}
}
The method signature public static double CelciusToFarenheit(...) says that this method returns a value - and currently it does.
However, your program flow has to consider invalid input - and thus you need 2 information:
was the entered value a valid value
what's is the value
There are different methods to solve this issue, at least the following:
return a struct or object that holds both information
use the return value and indicate invalid results with exceptions
split the single method into 2 methods, one for checking validity and one for delivering the value.
Let's discuss the 3 options:
3) This might be looking nice, but when you look at Double.TryParse(), you'll likely introduce duplicate code. And when you look at the Main method, the abstraction level will not be the same.
2) Exceptions shall be used for exceptional cases. Wrong user input seems to be a rather usual thing. Not ideal for this case.
1) Sounds quite ok, except that the method might be responsible for 2 things: checking validity and calculating.
To implement that, you don't even need to write a new struct or class. You can simply use Nullable<double> or double?.
Since you're talking about clean code (potentially referring to R.C. Martin), I would start by looking at the main method. Basically I would say the code follows the IPO principle (input, processing, output). However, one line does 2 things:
var input = CelciusToFarenheit(Console.ReadLine());
Also, the variable name input is not so useful here, because it's not the input of the user, but the output after processing.
Proposal for that part:
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
Also, the conversion method does not only convert, but print partial results as well:
Console.WriteLine("Invalid code");
I'd remove that piece and leave it to the output method to handle that case.
Full code:
using System;
namespace CSharpBasics
{
class Program
{
public static double? CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
else
{
return null;
}
}
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
private static void PrintOutput(double? output)
{
if (output == null)
{
Console.WriteLine("Invalid code");
}
else
{
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + output);
}
}
private static string GetCelsiusInputFromUser()
{
Console.WriteLine("Please enter a celsius value for conversion:");
var userInput = Console.ReadLine();
return userInput;
}
}
}
BTW: if you don't have a technical issue, https://codereview.stackexchange.com/ might be better suited for questions regarding clean code.
Ahoy! I have just started methods but I am a tad confused when it comes to methods with math. First post so be nice :) I'm aware I out in NumberToSquare way too many times!
Write a program that asks the user to enter a number. In your program write a function called SquareValue that takes an integer parameter and calculates the square of integer parameter and returns this squared value. Your program should take this returned square value and display it. An example of the output is:
Please enter a number to square: 8
/ 8 squared is: 64
What I have so far is not so comprehensible. I thought along a few different avenues and was unsure as to what to delete. Help please.
namespace SquareValue
{
class Program
{
static void Main(string[] args)
{
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
string output;
Console.ReadKey();
}
public int SquareValue(NumberToSquare, NumberToSquare);
{
int result = NumberToSquare * NumberToSquare;
return result;
Console.WriteLine("{0} squared is "+result");
}
public int NumberToSquare()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = Console.ReadLine();
return NumberToSquare;
}
}
I see no reason to over complicate this:
public int Square(int x)
{
return (x * x);
}
or
public int Square(int x)
{
return Math.Pow(x,2);
}
Or just use Math.Pow as it exists with 2 as the Power Of number.
You seem very green on programming and I'm not sure SO is a place to go to learn the basics, but I'll run through what you've done and explain what's going wrong.
Your original program concept is fine but there are many issues with basic syntax. I understand you mightn't be familiar with reading compiler errors so I'll explain the errors that I see just reading through the code...
You put a ; at the end of the SquareValue(..., ...) method which teeminates the declaration so the body in braces isn't part of the method, then things go haywire later on.
You're not passing in the value captured from the NumberToSquare method...
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
NumberToSquare isn't a defined variable so NumberToSquare * NumberToSquare can't calculate, what you'd want is number * number where `number is the value entered by the user.
Your definition of int SquareValue(NumberToSquare, NumberToSquare) expects two parameters although you haven't speified the type. It should be
int SquareValue(int NumberToSquare, int NumberToSquare)
but you have the same variable declared twice which is another error and then you aren't passing two parameters anyway. You want to multiply a number by itself therefore you only have a single source number so why declared two parameters? You need a single parameter method
int SquareValue(int NumberToSquare)
and call like this
int number=NumberToSquare();
SquareValue(number);
Now the SquareValue() method returns an int but you never capture it in the calling code and display the result in the method. Follow the idea in this app that the Main method will do all the orchestration and display, but the SquareValue() method should ONLY do a calculation and not any I/O. I'd also rename the NumberToSquare() method a as what is actually happening ... GetNumberToSquareFromUser().
And there's also a stray " before the closing bracket.
Console.WriteLine("{0} squared is " + result");
And you defined a string output variable which is never used.
And your methods need to be static because main(..) is a static method, not instance. If you declare a Squaring class and instantiated it then you could call non static methods from that.
Also ReadLine() returns a string which can't be assigned to an int.
And finally the result line is implicitly using String.Format behind the scenes but you haven't specified the original number for the {0} token. You could also use interpolation. You could do either of these
Console.WriteLine("{0} squared is " + result, number);
Console.WriteLine($"{number} squared is " + result);
So here's your program revised
class Program
{
static void Main(string[] args)
{
int number = GetNumberToSquareFromUser();
int result = SquareValue(number);
Console.WriteLine("{0} squared is " + result, number);
Console.ReadKey();
}
public static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
public static int GetNumberToSquareFromUser()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = int.Parse(Console.ReadLine());
return NumberToSquare;
}
}
I hope this help, I know it's alot to take in, but I hope you take the time to read and really understand rather than just blindly submit the revised version.
When writing your methods, make them reusable. When you start using a method to output to the console in addition to its primary purpose (i.e. to square a number), its re-usability becomes minimal. It is much better to keep specific code in your main method, and put sub tasks into separate methods, such as squaring a number. Now, whenever you need to square a number, you already have a perfectly good method for that.
I didn't handle the case for users entering bad input, but that can be done in the else of the TryParse if block.
static void Main(string[] args)
{
int squredNum = 0;
int NumberToSquare = 0;
Console.WriteLine("Please enter a number to square: ");
if(int.TryParse(Console.ReadLine(), out NumberToSquare))
{
squredNum = SquareValue(NumberToSquare);
Console.WriteLine("{0} squared is {1}", NumberToSquare, squredNum);
}
Console.ReadKey();
}
static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
p.s. I would not recommend using Math.Pow() to square a number. No need to kill a fly with a bazooka!
Here is an example of such program with robust handling:
using System;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter value to square or X to exit");
var line = Console.ReadLine();
if (line == null)
continue;
if (line.Trim().Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Exitting ...");
break;
}
int result;
if (!int.TryParse(line, out result))
continue;
Console.WriteLine(result * result);
}
}
}
}
See the docs online, understand each statement, write your very own program then as your teacher will likely figure out you didn't pull that solely by yourself :)
I want to get input from user and print the type of the input given by user.
I have tried this.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
var userObj = Console.ReadLine();
// if input is 5 it should print it is of type int.
//if input is 5.4 it should print it is of type double.
Console.WriteLine(userObj.GetType());// printing only string
}
}
also tried this but always going false
using System;
class Solution
{
static void Main(String[] args)
{
var userObj = Console.ReadLine();
if (string.Format(userObj) == string .Format("0"))
{
Console.WriteLine("it is of type interger");
}
}
}
You're misunderstanding how var works in C#. C# is a strongly-typed language and as such it's not the same as other languages that use var like JavaScript. Therefore, the variable declared as var already knows what type it is at compile time.
Console.ReadLine() returns a string, therefore the variable userObj in this sense WILL be a string. You will never get anything but a string type.
You can, however, try several things to see if you can convert it to another type. for example:
var userInput = Console.ReadLine();
int x;
if(int.TryParse(userInput, out x))
{
Console.WriteLine("That's an int!");
}
Try parse some with some different number datatypes from biggest to smallest. I assume you want to store the number in the smallest one possible.
float var1;
double var2;
int var3;
if (float.TryParse(urMom, out var1))
Console.WriteLine("Float");
else if (double.TryParse(urMom, out var2))
Console.WriteLine("Double");
else if (int.TryParse(urMom, out var3))
Console.WriteLine("Int");
I am attempting to understand how methods work, and I thought that I had it down but it seems that I do not as my RunSelect(); method is not doing what I hoped. On line #19, I ask the user to select value (1 or 2) and return that as an int (Run). Then on line #25 we do an if/if else/else statement depending on the int selected. regardless of what is selected, the int is not recognized and asks the user to try again - no matter what i enter, it is not recognized so my console methods fail and I am not sure what it is I am doing wrong.
I've tried tracing through my code, printing it out to analyze it, took the night to sleep on it. etc. I'm lost as to why it's not working. I'm newb, any help greatly appreciated. I don't think the problem is with my loops or methods, i think it's in how i'm handing off the int to the if statement. But i'm lost as to why it's not working as i thought it would.
thanks and cheers to all for any help
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a032_Factorial_Fibonacci_Sequencer
{
class Program
{
String command = "";
//Need to get the runSelect to work as method
public void Play()
{
Announcer("+ + + Welcome To MegaCorps Factorial Fibioci Sequencer + + +\n\n");
int run = 0;
do
{
RunSelect(run);
if (run == 1) { RunFact(); }
else if (run == 2) { RunFib(); }
else
{
Announcer("Non Valid Selection");
RunSelect(run);
}
Announcer("Enter 'Y' to Run another sequence? ");
command = Console.ReadLine().ToLower().Trim();
}
while (command == "y" || command == "yes");
}
//HelperMethods
public String Announcer(String strTxt)
{
Console.WriteLine(strTxt);
return strTxt;
}
public int RunSelect(int run)
{
Announcer("Enter '1' to run Factor | Enter '2' to run Fibioci");
run = int.Parse(Console.ReadLine());
return run;
}
public void Closer()
{ Console.Read(); }
public void RunFact()
{
//craft program to factor a number entered and return factor
//use double not int to handle factored numbers larger then 57+
Console.WriteLine("Factorial Sequencer Entered/n/n");
Announcer("Enter A Number to FACTOR: ");
double num = double.Parse(Console.ReadLine());
double numNew = 1;
for (int i = 1; i <= num; i++)
{ numNew = numNew * i; }
Announcer("\nFACTORED result: " + numNew);
}
public void RunFib()
{
//craft program to fib a number entered and return fib
//use double not int to handle factored numbers larger then 57+
Console.WriteLine("Fibioci Sequencer Entered\n");
Announcer("Enter A Number to FIBIOC: ");
double iSequence = double.Parse(Console.ReadLine());
Announcer("\nFIBIOC result: ");
double iPrevious = -1;
double iNext = 1;
for (int i = 1; i <= iSequence; i++)
{
double iSum = iNext + iPrevious;
iPrevious = iNext;
iNext = iSum;
Console.Write(iNext + ", ");
}
}
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
}
}
}
Problem : you are not storing the return value of the RunSelect() method.
Solution : You need to store the return value of the RunSelect() Method.otherwise variable run value will not be modified (still zero even after calling RunSelect() method).
Replace This:
RunSelect(run);
WIth This:
run=RunSelect(run);
EDIT: if you are calling a method which returns something then you need to read/store the return value of that method as it contains modified value.
Step 1: in your code you have initialised variable run using following statement:
int run = 0;
Step 2: inside do-while loop you have called RunSelect() method as below:
do
{
RunSelect(run);
------
Step 3: in the method RunSelect() you are assigning the run variable with actual userinput given from console using following statements:
Note: here run variable in RunSelect() method is local variable to that method so even if you assign value to run it wont be reflected to run variable declared in Play() function.
public int RunSelect(int run)
{
Announcer("Enter '1' to run Factor | Enter '2' to run Fibioci");
run = int.Parse(Console.ReadLine());/here you are assigning userinput to run variable.
return run;
}
Step 4: you are sending back the modified variable value run to the caller of this method(RunSelect()):
Step 5: there you are not storing this return value sent by RunSelect() method again into run variable as below:
RunSelect(run);
so still run variable will have the initialised value zero.
to make it work you need to just store the return value of the RunSelect() method as below:
run=RunSelect(run);
You have a Function which accepts a value parameter and returns an int, but you aren't assigning the return int to anything. In your case, the parameter is redundant, since it isn't used within the method anyway. in C#, by default, parameters are value parameters. This means that a new storage location is created for the variable in the function member declaration, and it starts off with the value that you specify in the function member invocation. If you change that value, that doesn't alter any variables involved in the invocation.
try this instead:
public int RunSelect()
{
Announcer("Enter '1' to run Factor | Enter '2' to run Fibioci");
int run = int.Parse(Console.ReadLine());
return run;
}
and in your method call:
int run = RunSelect();
no need to pre-initialize run before the call, so you can remove the line int run = 0;
When you call RunSelect(run), you are not changing the current value of run. Passing in run cannot change its value. The RunSelect function returns a new value that you have to assign like this: run = RunSelect(run).
Also you will notice that RunSelect does not use the value of run that is passed in, so it can just as easily be written like this:
public int RunSelect()
{
Announcer("Enter '1' to run Factor | Enter '2' to run Fibioci");
int run = int.Parse(Console.ReadLine());
return run;
}