The problem stands at line 23 and 25.
double r.length = Convert.ToDouble(Console.ReadLine());
double r.width = Convert.ToDouble(Console.ReadLine());
I don't know how to make the conversion from string to double so that the program would take double numbers from the user.
My programming teacher once made it but I forgot to note it.
class Rectangle
{
double length;
double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: "+length);
Console.WriteLine("Width: "+ width);
Console.WriteLine("Area: "+ GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine("Length= ");
double r.length = Convert.ToDouble(Console.ReadLine()); // <===
Console.WriteLine("Width= ");
double r.width = Convert.ToDouble(Console.ReadLine())); // <===
Console.Writeline("Area= ");
r.Display();
Console.ReadLine();
}
}
There are a couple things to fix:
Rectangle
Both length and width should be public
Both length and width should be properties
I.e., they should have { get; set; } appended
The names for both length and width should be capitalized because they are properties
This is a C# naming convention
Override ToString() for creating a description/string for an object
ExecuteRectangle
You don't need the double keyword when referencing r.length and r.width in ExecuteRectangle
To convert a string to a double, use double.TryParse
class Rectangle
{
public double Length { get; set; }
public double Width { get; set; }
public double GetArea()
{
return Length * Width;
}
public override string ToString()
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Length: " + Length);
stringBuilder.AppendLine("Width: " + Width);
stringBuilder.Append("Area: " + GetArea());
return stringBuilder.ToString();
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine("Length= ");
double.TryParse(Console.ReadLine(), out r.Length);
Console.WriteLine("Width= ");
double.TryParse(Console.ReadLine(), out r.Width);
Console.Writeline("Area= " + r.GetArea());
Console.WriteLine(r.ToString());
Console.ReadLine();
}
}
Besides what Amir Arbabian has stated in his answer, there is another problem. The protection level for Rectangle.width and Rectangle.length are not specified, so they default to private. To make it accessible, add the public keyword before the length and width fields in Rectangle.
public double length;
public double width;
One last thing is that you have an extra closing parentheses ()) on the line
double r.width = Convert.ToDouble(Console.ReadLine()));
Simply remove one of the closing parentheses to remove that error. And remove the double keyword, as Amir Arbabian has stated.
Also, what do you need that last Console.ReadLine() for?
You have to write it as
r.width = Convert.ToDouble(Console.ReadLine());
without double keyword.
You use type only when you declare something, but here you just assign value to field of object.
Hope that helps.
Related
I'm building a pythagoras calculator in c# for school, but I can't figure out how I should change the lines: s1 = 3; and s2 = 4; into lines that ask for user input. Not only that, I also need to use a function to calculate the pythagorean. Any help is appreciated because I'm totally lost, thank you!
using System;
public class Pythagorean {
public static void Main() {
double s1;
double s2;
double hypot;
s1 = 3;
s2 = 4;
hypot = Math.Sqrt(s1*s1 + s2*s2);
Console.WriteLine("The length of side c is " + hypot);
}
}
You can use Console.ReadLine() - your value will be read into variable (if parsed) after pressing Enter:
using System;
public class Pythagorean {
public static void Main() {
double s1;
double s2;
double hypot;
if (double.TryParse(Console.ReadLine(), out s1) && double.TryParse(Console.ReadLine(), out s2))
{
hypot = Math.Sqrt(s1*s1 + s2*s2);
Console.WriteLine("The length of side c is " + hypot);
}
else
{
Console.WriteLine("Invalid input - entered values cannot be parsed to double");
}
}
}
The code can be simplified (inline variable declarations):
using System;
public class Pythagorean {
public static void Main() {
if (double.TryParse(Console.ReadLine(), out var s1)
&& double.TryParse(Console.ReadLine(), out var s2))
{
var hypot = Math.Sqrt(s1*s1 + s2*s2);
Console.WriteLine("The length of side c is " + hypot);
}
else
{
Console.WriteLine("Invalid input - entered values cannot be parsed to double");
}
}
}
using System;
public class Pythagorean
{
public static void Main()
{
Console.Write("Enter s1: ");
double s1 = double.Parse(Console.ReadLine());
Console.Write("Enter s2: ");
double s2 = double.Parse(Console.ReadLine());
double hypot = Math.Sqrt(s1 * s1 + s2 * s2);
Console.WriteLine("The length of side c is " + hypot);
}
}
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
WriteLine("The area of your circle is: " +
circleArea(Double.Parse(ReadLine())).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
I thought I had it set up correctly; however, I receive an error of System.FormatException: 'Input string was not in a correct format. on the line WriteLine("The area of your circle is: " + circleArea(Double.Parse(ReadLine())).ToString()); when no value is entered. I would like it to have a default value of 2. Thanks.
Your problem is that you need to split out the conversion to be able to test for a bad input condition. Take a look at this code.
Console.WriteLine("What is the radius of your circle: ");
var isNumber = Double.TryParse(Console.ReadLine(), out double number);
if (!isNumber)
number = 0;
Console.WriteLine("The area of your circle is: " + circleArea(number).ToString());
Console.ReadKey();
This will test for a legitimate number and if it's not, it just passes zero as the number.
Double.Parse() will always throw a FormatException if the input is not in the form of a valid double.
The behavior of default parameter values is that omitting the parameter when calling the method will cause it to instead use the default value (this is done by inserting the default value into the method call at compile-time). There is no language behavior which would enable an invalid value to be automatically replaced by some default.
In your case, you need to preempt the empty value which is going to Double.Parse(). Something like this:
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
if (!double.TryParse(input, out var value))
WriteLine($"Invalid input received: {value}");
else
WriteLine("The area of your circle is: " + circleArea(value).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
Here's a concise way of testing the input and selecting a default if whatever was input is in an incorrect format.
Console.Write("What is the radius of your circle: ");
var value = double.TryParse(Console.ReadLine(), out var input) ? input : 2d;
Console.WriteLine($"The area of your circle is {circleArea(value)}");
I'd highly advice to do the reading and calculation in two steps
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
double d = 0.0;
if(!Double.TryParse(input,out d)) {
d = //default value here
}
WriteLine("The area of your circle is: " + circleArea(d).ToString());
ReadKey();
}
}
I am trying to build a BMI calculator and I the only thing that can be in the main function is method calls. Whenever i run the following code, the calculation answer does not print. How can i fix that?
public static Double EnterWeight(object sender, EventArgs e)
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight(object sender, EventArgs e)
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight(object sender, EventArgs e);
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
Console.WriteLine("Your BMI is: ", BMI);
}
There are some extra lines in the mine that I used for testing.
The result is just a blank
It looks like there are several problems with the code, though they are small. First, you define methods that take in parameters that are not used, like object sender and EventArgs e. You should only define arguments to a method if they are used inside the method, so you can remove those in your case.
Secondly, when you call EnterWeight, you're defining the variables inside the method call, rather than defining them before-hand and then passing them in using the variable names (which would be the way to solve this issue). But since the method doesn't actually require them, they can be removed from the method and therefore removed from the call.
Finally, when writing methods to get strongly-typed input from the user, it is sometimes nice to create a more flexible method that takes in a string used for the "prompt" for the input, and then use the TryParse methods in a loop, which continually loops until they enter valid input. This way you can re-use the same method to get a double from the user and just pass in different prompts.
For example:
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
private static double GetDoubleFromUser(string prompt)
{
double input;
// double.TryParse attempts to convert a string into a double, and
// it returns a bool that indicates success. If it's successful,
// then the out parameter will contain the converted value. Here
// we loop until we get a successful result, then we return the value.
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out input));
return input;
}
public static double GetBMI(double height, double weight)
{
return weight / Math.Pow(height, 2) * 703;
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static void Main()
{
string name = GetStringFromUser("Enter your name: ");
double weight = GetDoubleFromUser("Enter your weight in pounds: ");
double height = GetDoubleFromUser("Enter your height in inches: ");
double bmi = GetBMI(height, weight);
Console.WriteLine($"Thank you, {name}. Your BMI is: {bmi}");
GetKeyFromUser("\n\nDone! Press any key to exit...");
}
You are using the Console.WriteLine incorrectly. You need to use {argumentNumber} to indicate what argument to print and where in the string. Considering the following (I had to make some additional adjustments to get your code to compile. However, to answer your direct question, your BMI is not printing out because you are using Console.WriteLine slightly wrong.
public static Double EnterWeight()
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight()
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
//string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight();
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
// Notice the {0}. I tell it where in the string to print the
// argument I passed in out, and the number indicates which argument
// to use. Most of .NET formatting works like this.
Console.WriteLine("Your BMI is: {0}", BMI);
}
And additional strategy is to use the $"" string where you can do the following:
Console.WriteLine($"Your BMI is: {BMI}");
I have a string (like below), and I want each of the argument to be center aligned.
There is an option for left align that is ("+") and right align that is ("-") but I want to center align.
basketItemPrice = string.Format("\n\n{0, -5}{1, -14:0.00}{2, -18:0.00}{3,-14:0.00}{4,6}{5,-12:0.00}", item.Quantity, item.OrderItemPrice, item.MiscellaniousCharges, item.DiscountAmountTotal, "=", item.UpdateItemAmount(Program.currOrder.OrderType));
Unfortunately, this is not supported natively by String.Format. You will have to pad your string yourself:
static string centeredString(string s, int width)
{
if (s.Length >= width)
{
return s;
}
int leftPadding = (width - s.Length) / 2;
int rightPadding = width - s.Length - leftPadding;
return new string(' ', leftPadding) + s + new string(' ', rightPadding);
}
Usage example:
Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10)));
Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
I tried to make an extension method which still preserves the IFormattable support. It uses a nested class which remembers the raw value and the desired width. Then when format string is provided, it is used, if possible.
It looks like this:
public static class MyExtensions
{
public static IFormattable Center<T>(this T self, int width)
{
return new CenterHelper<T>(self, width);
}
class CenterHelper<T> : IFormattable
{
readonly T value;
readonly int width;
internal CenterHelper(T value, int width)
{
this.value = value;
this.width = width;
}
public string ToString(string format, IFormatProvider formatProvider)
{
string basicString;
var formattable = value as IFormattable;
if (formattable != null)
basicString = formattable.ToString(format, formatProvider) ?? "";
else if (value != null)
basicString = value.ToString() ?? "";
else
basicString = "";
int numberOfMissingSpaces = width - basicString.Length;
if (numberOfMissingSpaces <= 0)
return basicString;
return basicString.PadLeft(width - numberOfMissingSpaces / 2).PadRight(width);
}
public override string ToString()
{
return ToString(null, null);
}
}
}
Note: You have not indicated if you want the one "extra" space character put to the left or to the right in cases where an odd number of space characters needs to be appended.
This test seems to indicate it works:
double theObject = Math.PI;
string test = string.Format("Now '{0:F4}' is used.", theObject.Center(10));
Of course, format string F4 with a double means "round to 4 decimal places after the decimal point".
I am not sure to understand your question but I hope this helps you:
public static class StringHelper
{
public static string Center(this String value, int width)
{
var padding = (width + value.Length) / 2;
return value.PadLeft(padding, '#');
}
}
If you are drawing onto a bitmap use Graphics.DrawString(..) method with a string alignment set to center.
Plenty of examples here:
http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.linealignment.aspx
I've a String with Length = 100;
I need to center the text "Hello", in that string using whitespaces.
How can i do ?
thanks.
You can use the string padding methods and a little match to calcualte the center position:
var stringToCenter = "hello";
var totalLength = 100;
var centeredString =
stringToCenter.PadLeft(((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length)
.PadRight(totalLength);
And you can move this logic into an extension method:
public static class StringExtensions{
public static string CenterString(this string stringToCenter, int totalLength)
{
return stringToCenter.PadLeft(((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length)
.PadRight(totalLength);
}
}
And you can use it like
var centeredString = "hello".CenterString(100);
Demo .NETFiddle.
I would have added this as a comment to #nemesv's answer, but my lack of reputation on Stack Overflow prevents it.
The code in that answer causes more padding to be added on the right than the left. For example, in the code for that answer, the "h" in hello appears at the 43rd position instead of the 48th.
This revised code balances the padding.
var stringToCenter = "hello";
var stringToCenterLength = stringToCenter.Length;
var totalLength = 100;
var centeredString = stringToCenter.PadLeft(((totalLength - stringToCenterLength) / 2) + stringToCenterLength).PadRight(totalLength);
You can calculate string lenght and then apply appropriate padding by:
"".PadLeft() or "".PadRight()
I've expanded #nemesv's answer to contain an overload accepting a padding character so you can get something like:
################################# Hello World! #################################
Code:
using System;
public class Program
{
public void Main()
{
Console.WriteLine(" Hello World! ".CenterString(80, '#'));
}
}
public static class StringExtensions
{
public static string CenterString(this string stringToCenter, int totalLength)
{
return stringToCenter.PadLeft(
((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length).PadRight(totalLength);
}
public static string CenterString(this string stringToCenter,
int totalLength,
char paddingCharacter)
{
return stringToCenter.PadLeft(
((totalLength - stringToCenter.Length) / 2) + stringToCenter.Length,
paddingCharacter).PadRight(totalLength, paddingCharacter);
}
}
Example: .NETFiddle