I'm obviously a newbie when it comes to C# and the following program is from a Charles Petzold book that I don't fully understand. The parameter in the GetDouble method is a string named prompt. Nowhere is this declared and I think that's what's messing me up. I see that the Main method is calling GetDouble and is printing three strings to the console, but this whole thing looks weird to me. Is this typical programming design, or is this not industry standard, but for purposes of showing how things can be done? The book doesn't give an answer either way. My fledgling programming self wouldn't pass a string to the Main method. Can someone help straighten me out?
using System;
class InputDoubles
{
static void Main()
{
double dbase = GetDouble("Enter the base: ");
double exp = GetDouble("enter the exponent: ");
Console.WriteLine("{0} to the power of {1} is {2}", dbase, exp, Math.Pow(dbase, exp));
}
static double GetDouble(string prompt)
{
double value = Double.NaN;
do
{
Console.Write(prompt);
try
{
value = Double.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine();
Console.WriteLine("you enter an invalid number!");
Console.WriteLine("please try again");
Console.WriteLine();
}
}
while (Double.IsNaN(value));
return value;
}
}
Nowhere is this declared and I think that's what's messing me up.
Wait, it's declared right there - in the header of the method:
static double GetDouble(string prompt)
// ^^^^^^^^^^^^^ This is the declaration of prompt
prompt is different from other variables that you have seen in that it is not a normal variable: it is a formal parameter of a method.
Unlike regular variables which you initialize and assign explicitly with the assignment operator =, formal parameters are assigned implicitly by virtue of calling a method. When you call the method, you pass it an expression with the actual parameter, which acts as an assignment of that expression to the formal parameter. Imagine that the prompt variable is assigned "Enter the base: " before the first call, and then it is assigned "enter the exponent: " before the second call to understand what is going on when you call GetDouble.
The GetDouble(string) method does just that - it gets a double from the input.
The text that is prompted to the user is a parameter, because there are two different values to be entered: first the base number, second the exponent.
By making the prompt a parameter, the GetDouble(string) method can handle everything from prompting the user for input to returning the value.
The alternative would be to prompt the user outside of GetDouble(string). Which of these two options is preferable is a matter of taste.
Oh, and as you've probably figured by now, this has nothing to do with the exception handling in the method.
You can change it this way. It does the same but I think more understandable:
static void Main()
{
string messageForDbaseParam="Enter the base: ";
double dbase = GetDouble(messageForDbaseParam);
string messageForExpParam ="enter the exponent: ";
double exp = GetDouble(messageForExpParam);
Console.WriteLine("{0} to the power of {1} is {2}", dbase, exp, Math.Pow(dbase, exp));
}
static double GetDouble(string prompt)
{
double value = Double.NaN;
Boolean incorrectValue=true;
while(incorrectValue)
{
Console.Write(prompt);
try
{
value = Double.Parse(Console.ReadLine());
incorrectValue=false;
}
catch
{
Console.WriteLine("error");
}
}
return value;
}
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 have an application assignment from school that I have been working on and have gotten stuck on. I am not understanding some of the concepts to complete my program. It is simple and I have the basic structure down. Could someone assist me in understanding and completing my program? Below is the listed information:
The following is the overall application assignment:
Write a program to display the average of some numbers. Your program will consist of three user defined methods named GetNums(), CalcAvg(), and DspAvg(). In GetNums() prompt for and read in 3 real numbers from the keyboard. After reading in the numbers, call CalcAvg() passing the three numbers as input. CalcAvg() must RETURN (use the return statement) the average of the 3 numbers. After calling CalcAvg(), call DspAvg() to display the average and the three numbers entered. Your program must not contain any variables with class-wide scope (all variables must be declared inside a method). All method calls (GetNums(), CalcAvg(), and DspAvg() must be called from main()). Using proper passing is important.
Your output should closely resemble the following.
The average of 10.20, 89.50, and 17.60 is 39.10.
Round the average to two decimal places. Display all values with two decimal places.
GetNums() will have three arguments, all pass by out. CalcAvg() will have three arguments, all pass by copy. Do not use four! DspAvg() will have four arguments, all pass by copy.
Below is the following code I have written, but have gotten stuck, based on the requirements above.
static void Main(string[] args)
{
int nu1, nu2, nu3, cavg;
GetNums();
CalcAvg();
DspAvg();
}
static void GetNums()
{
Console.Write("Please enter nu1: ");
nu1 = int.Parse(Console.ReadLine());
Console.Write("Please enter nu2: ");
nu2 = int.Parse(Console.ReadLine());
Console.Write("Please enter nu3: ");
nu3 = int.Parse(Console.ReadLine());
CalcAvg(DspAvg);
}
static void CalcAvg()
{
}
static void DspAvg()
{
}
}
}
You can't declare variables in one method and use them in another method. the second method doesn't know the variables in the first method.
As the specification said you need your GetNums() to have 3 parameters passed by out
static void GetNums(out decimal num1, out decimal num2, out decimal num3)
Start from here. If you need more help please let me know :)
Well, we won't do your homework for you, but I can give you a few pointers. Your Main should only call GetNums(). GetNums() should call CalcAvg() passing in the numbers read from the console not the DspAvg() function. Finally pass the returned value from CalcAvg() to DspAvg() to display the result to the console.
Start writing some code and if you are getting errors, then we will be able to help you more.
You are not using parameters as described in the assignment. Here is an example of using an out parameter with one method and sending it into another method and returning a value:
double parameter, result;
methodOne(out parameter);
result = methodTwo(parameter);
The methods:
static void methodOne(out double x) {
x = 42;
}
static double methodTwo(double x) {
return x;
}
That should get you started on how you need to modify your methods.
I will provide some suggestions, but this a very good introductory programming problem. I would very much recommend trying to solve this problem on your own as it uses basic programming concepts that you will use in the future.
Your variables nu1, nu2, nu3, and cavg should be double values. An int can not be used to store decimal values. (Note: to get a value with 2 decimal places, you should use the Math.Round method)
double nu1, nu2, nu3, cavg;
You seem to be stuck on how to pass paramaters to a method. For example, when you call the CalcAvg method in your main method, you should be passing the 3 values you read from the console into the method.
static void Main(string[] args){
CalcAvg(nu1,nu2,nu3);
}
static void CalcAvg(double nu1, double nu2, double nu3){
}
By doing this, you can now manipulate the values within your CalcAvg method.
Finally, once you have passed values into a method and manipulated them, you will want to return these values from the method. This can be done with the return statement. You can then call this method by passing in your paramaters and storing the returned value in another variable.
static void Main(string[] args){
double cavg;
cavg = CalcAvg(nu1,nu2,nu3);
}
static double CalcAvg(double nu1, double nu2, double nu3){
double cavg;
return cavg;
}
These three principles should help you complete this assignment. I STRONGLY recommend you do this assignment on your own and not copy the complete answer off of this or any other website. Learning these principles correctly will help you further down the road in your academic career. Good luck :)
I've made a few assumptions here. But I've gone ahead to give you a "working" app for you to consider
static void Main(string[] args)
{
int nu1, nu2, nu3, cavg;
GetNums(out nu1, out nu2, out nu3);
double average = CalcAvg(nu1, nu2, nu3);
DspAvg(average);
}
static void GetNums(out int nu1, out int nu2, out int nu3)
{
Console.Write("Please enter nu1: ");
nu1 = int.Parse(Console.ReadLine());
Console.Write("Please enter nu2: ");
nu2 = int.Parse(Console.ReadLine());
Console.Write("Please enter nu3: ");
nu3 = int.Parse(Console.ReadLine());
}
static double CalcAvg(int nu1, int nu2, int nu3)
{
return (nu1 + nu2 + nu3) / 3;
}
static void DspAvg(double average)
{
Console.WriteLine(Math.Round(average, 2));
}
I am trying to make improve my programming and getting things drilled into my head so I'm just quickly developing an application that gets user's input and prints their name. But also gets their input for "Age verification".
I'm practicing IF & ELSE statements as well as nesting classes.
However my compiler is shooting me an error and I just cannot seem to figure it out. I'm trying to get the user to input his age, and then proceed with the IF & ELSE statement.
Compiler is shooting error that . ""Cannot implicitly convert type
string to int"
The only error in the program right now is the
myCharacter.age = Console.ReadLine();
using System;
namespace csharptut
{
class CharPrintName
{
static void Main()
{
Character myCharacter = new Character();
Console.WriteLine("Please enter your name to continue: ");
myCharacter.name = Console.ReadLine();
Console.WriteLine("Hello {0}!", myCharacter.name);
Console.WriteLine("Please enter your age for verification purposes: ");
myCharacter.age = Console.ReadLine();
if (myCharacter.age <= 17)
{
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
}
else if (myCharacter.age >= 18)
{
Console.WriteLine("You can enter!");
}
}
}
class Character
{
public string name;
public int age;
}
}
As the error says you can't implicitly type a string to an int. You need to parse it into an int.
string input = Console.ReadLine();
int age;
if (int.TryParse(input, out age)
{
// input is an int
myCharacter.age = age;
}
else
{
// input is not an int
}
You are trying to assign a string value to an int with this line:
myCharacter.age = Console.ReadLine();
Try:
myCharacter.age = Int32.Parse(Console.ReadLine());
character.age expects an Int but ReadLine() returns a string, you need to look at using int.Parse or int.TryParse to avoid exceptions
e.g.
if (!int.TryParse(Console.ReadLine(),out myCharacter.age)) {
Console.WriteLine("You didn't enter a number!!!");
} else if (myCharacter.age <= 17) {
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
} else {
Console.WriteLine("You can enter!");
}
This looks like a student project.
The input coming from the ReadLine() is always of type string. You're then comparing a string to 17 which isn't valid, as 17 is an int. Use TryParse versus parse to avoid throwing an exception at runtime.
string typedAge = Console.ReadLine();
int Age = 0;
if (!int.TryParse(typedAge, out Age))
Console.WriteLine("Invalid age");
if (Age <= 17)
Console.WriteLine("You're awfully young.");
OK. The problem here is that the age is defined as an int and Console.ReadLine() always returns a string so thus you have to convert the user input from string to integer in order to correctly store the age.
Something like this:
myCharacter.age = Int32.Parse(Console.ReadLine());
When you read input from the console, it returns it to you in the form of a string. In C#, which is a statically typed language, you cannot simply take one type and apply it to another type. You need to convert it somehow, there are several ways to do this.
The first way would be casting:
myCharacter.age = (int)Console.ReadLine();
This won't work because a string and an integer are two completely different types and you can't simply cast one to the other. Do some reading on casting types for more information.
The second way would be to convert it, again there are a couple of ways to do this:
myCharacter.age = Int32.Parse(Console.ReadLine());
This will work as long as you type in an actual number, in this case the Parse method reads the string and figures out what the appropriate integer is for you. However, if you type in "ABC" instead, you will get an exception because the Parse method doesn't recognize that as an integer. So the better way would be to:
string newAge = Console.ReadLine();
int theAge;
bool success = Int32.TryParse(newAge, out theAge);
if(!success)
Console.WriteLine("Hey! That's not a number!");
else
myCharacter.age = theAge;
In this case the TryParse method tries to parse it, and instead of throwing an exception it tells you it can't parse it (via the return value) and allows you to handle that directly (rather than thru try/catch).
That's a little verbose, but you said you're learning so I thought I'd give you some stuff to consider and read up on.