I am modifying a simple c# program that shows the area of a rectangle whose width and height you write in the console(initially the width and height's values were given in the program).However, the user input part doesn't seem to work.I have tried Convert.ToInt32() and I even changed the variables to be integers even though they should be float's, thinking that the conversion will work that way, but to no avail.The error I get is :"error CS0266: Cannot implicitly convert type 'double' to 'int'.".
The question is, what do I do to make this work?I think I could just remove the function and just write the code in the main one, but I'm trying to learn to use the functions and I would be thankful if you could show me a way of giving the variable's value the keyboard input without removing the function.
'
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
//read length and width from the keyboard
length = Convert.ToDouble(Console.ReadLine());
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{ //display the length width and area
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
'
I would suggest using decimal.TryParse()
see this answer for details: Need help with accepting decimals as input in C#
Console.ReadLine() is a function you forgot ()
this should work
length = Convert.ToInt32(Console.ReadLine());
width = Convert.ToInt32(Console.ReadLine());
Related
I'm wondering if someone can help me with decimals? Im going to make a program there can wright price and how much you paid, and then get a change back, but i need to add decimals. The decimals have to round up or down, so if it is 0,11 it goes to 0, if it is o,20 it goes to 0,25. So it will round up to either 0,25, 0,50, 0,75 and later on 1. The change have too also show in which cash you get back, so like 100 bucks, 500 bucks, 50 bucks if you know what i mean. I dont know how to do. This is how long i come:
using System;
namespace inlämninguno
{
class Program
{
// Starting point of my "Change" program
static void Main(string[] args)
{
Console.WriteLine(Subtract()); // adding a subract variable in the beginning of the code
Console.Read();
}
// Using the double datatype to for the decimals
public static double Subtract()
{
Console.WriteLine("Price?"); // how much it costs
string number1Input = Console.ReadLine();
Console.WriteLine("Paid?"); // how much the customer pays
string number2Input = Console.ReadLine();
double prince = Convert.ToDouble(number1Input);
double paid = Convert.ToDouble(number2Input);
// This is for the subtracting part
double num1 = double.Parse(number1Input);
double num2 = double.Parse(number2Input);
double result = num2 - num1; // this is so the console subtracts the values, have to put num2 first so the output isn't negative
Console.Write("Your change is " + result + ":"); // Output "Your change is ..."
return result; // A method that gives the right output of the code
}
}
}
Can someone please help me? Im stuck :D
I tried to convert to double and lots of stuff, but I don't know how to do now.
I have an assignment that requires us to use arrays and not lists. I have two problems right now; one being that every time the user makes an input, the length of array playerNumber increases by one so I need it to be indefinite and I also need to send the array back to the main method. The code below works only once and when I try to enter a second input the program crashes.
int x = 0;
string answer = "yes";
string[] playerNumber = new string[] {};
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber = new string[] { y };
playerNumber[x - 1] = y;
x++;
Console.Write("Enter another number : ");
answer = Console.ReadLine();
Console.WriteLine();
}
It is not clear what your'e trying to do.
To start with, your index is out of bounds.
Your'e doing: playerNumber[x-1], but x == 0, so you get an exception. This is the only reason your code fails. Note that taking the ++x; one line up will also fail you, since in the second loop, playerNumber is again an array of size 1, but x value is now 2, and your'e again out of bounds.
Secondly, your'e initializing your array both outside and inside the while loop. You have no use of the outer initialization (and maybe there's no need for the inner one - again, depends on what exactly you're trying to achieve).
Thirdly, you should give the user the correct instruction: If you want answer to be yes or no, specify it in your Console.Write.
So if I managed to guess what you were trying to do, here's your code with a few changes, including the usage of Array.Resize (which is very inefficient in this context), and returning the array, as you asked:
using System;
public class Test
{
public static string[] MyFunc()
{
int x = 1;
string answer = "yes";
string[] playerNumber = new string[x];
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber[x-1] = y;
x++;
Array.Resize(ref playerNumber, x);
Console.Write("Would you like to enter another number? (yes/no)");
answer = Console.ReadLine();
Console.WriteLine();
}
return playerNumber;
}
public static void Main()
{
Console.WriteLine(MyFunc()[0]); // prints the first string
}
}
I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}
When I used {0} in following code:
class Program
{
double width;
double height;
public void getData() {
Console.WriteLine("Enter Width:");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Height:");
height = Convert.ToDouble(Console.ReadLine());
}
public double calcArea() {
return width * height;
}
public void display() {
Console.WriteLine("Area is : {0}",calcArea());
}
}
class Area
{
static void Main(string[] args)
{
Program p = new Program();
p.getData();
p.display();
}
}
The output was:
Enter Width:6Enter Height:9Area is : 54
And when I used {0} in this:
class NewArea
{
static void Main(String[] args) {
double width;
double height;
double area;
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Height: ");
height = Convert.ToDouble(Console.ReadLine());
area = width * height;
Console.WriteLine("Area is: {0}" +area);
}
}
The output was
Enter Width:4Enter Height:5Area is: {0}20
What does {0} mean?
There are two different meaning for {0} as you have used.
Console.WriteLine("Area is : {0}",calcArea());
In above sentence once you give {0} it means that you may provide some value after comma in same sentence as you provide the value 54 after comma so Console figured that and place that value at 0.
In similar way you can provide many values like
Console.WriteLine("Area for Width {0} and Height {1} is {2}",
width, height, calcArea());
OutPut: Area for Width 4 and Height 5 is 20
In another line you used it like
Console.WriteLine("Area is: {0}" +area);
As in this statement format did not find any comma after {0}" instead found + area so it replace varibale area with value and printed {0} as there is not any matching value {0} which should be given after comma like earlier statement.
It's a placeholder for the matching parameter in String.Format and WriteLine
For example:
String.Format("My name is {0} and I love {1}!", "Orel Eraki", "Snooker");
Output:
My name is Orel Eraki and I love Snooker!
String.Format(String,Object[])
The String argument obviously takes your string, then you can insert multiple object values although this is not necessary. The {0} is just a way to signify that the value of the first object argument will be placed there, similarly {1} means the second and {2} the third. It uses array index syntax.
if you write:
String.Format("Value = {0}",val);
and val is an integer with the value of 20 then the output will be:
'Value=20'
but if you write
String.Format("Value = {0}"+val)
then you are not giving two arguments to the method but only one, a concatenated string that consists of the "Value= {0}" string and the return value of the ToString() method of val.
Since there is no second argument the {0} is treated as just a part of the string and not as something with special meaning. That's why the output is: Value = {0}20
It injects the returning value of calcArea() into the string before printing it on the console window
If you use more than one parameter, you need to use {1}, {2}, etc. You might also use one parameter in more than one place by specifying e.g. {0} more than once.
Just see the example below,
static void Main()
{
int a=10;
int b=20;
Console.WriteLine(" The value of A is {0} " ,a);
Console.WriteLine(" The value of A is {0}, the Value of B is {1}",a,b);
Console.Read();
}
see the first WriteLine statement, i'm printing A alone. {0} is the place my printing variable will be seen in output. The same way i have written the second statement with two outputs {0}, {1} So it will be printed accordingly.
I am working on a project, Yes its for school. I'm having a hard time understanding how to pass the user input and store it with a array. The project is to get high and low temps for seven days and store in different arrays then compute the ave high etc. how do I collect the input and store it in a array in a different class? I think I almost have it but not sure where I'm going wrong
I have this so far but get a error:
Cannot implicitly convert type 'int' to 'int[]'
namespace Project_Console_3
{
class Program
{
static void Main(string[] args)
{
WeeklyTemperature Temp = new WeeklyTemperature();
int Count = 0;
while (Count < 7)
{
Console.WriteLine("Enter The High Temperature for Day {0}", Count+1);
Temp.HTemp1 =Console.ReadLine(); // save the number as a string number
Temp.HTemp = Convert.ToInt32(Temp.HTemp1); // change the string number to a integer as HTemp
Console.WriteLine("--------------------------------");//Draws a line
Console.WriteLine("Enter The Low Temperature for Day {0}", Count+1);
Temp.LTemp1 =Console.ReadLine(); // save the number as a string number
Temp.LTemp = Convert.ToInt32(Temp.LTemp1);
Console.WriteLine("--------------------------------");//Draws a line
Count = Count + 1;
Console.Clear();
}
}
}
}
WeeklyTemperature.cs
namespace Project_Console_3
{
class WeeklyTemperature
{
public int[] HTemp = new int[7];
public int[] LTemp = new int[7];
public string HTemp1;
public string LTemp1;
}
}
It looks like all you need to do is change this line:
Temp.HTemp = Convert.ToInt32(Temp.HTemp1);
to
Temp.HTemp[Count] = Convert.ToInt32(Temp.HTemp1)
Your error message tells you that you have a mismatch in the assignment of variables.
in this line:
Temp.HTemp = Convert.ToInt32(Temp.HTemp1);
The return value is of type int but the variable Temp.HTemp is of type int[] which is an array that holds individual integer.
To store values in an array the compiler has to know at which position it has to put the value.
Indexing an array works with the [] operators:
int pos = 0;
Temp.HTemp[pos] = 5;
will store a 5 on the first position.
Since you have a counting variable in your while loop you can use it to index the position where the numbers should be stored, as Jim Ross already showed in his answer.
More on the topic of indexing you can find here, and a tutorial is here