I'm bigener in C# programming
So, I was just wondering about how to take user input in the same line?
this is my code and also I want to print the output in the same line
using System;
namespace Wa2
{
class BodyMassCalculation
{
public static void Main (string[] args)
{
Console.WriteLine ("BMI Calculator\n");
double weight;
Console.WriteLine ("Enter your weight in kilograms: ");
weight = Convert.ToInt16(Console.ReadLine());
double height;
Console.WriteLine ("Enter your height in centimetres: ");
height = Convert.ToInt16(Console.ReadLine());
double meter;
meter = height / 100;
Double BMI;
BMI = (weight) / (meter*meter);
Console.WriteLine ("Your BMI is " , BMI);
Console.WriteLine(BMI.ToString("00.00"));
}
}
}
Try this:
Console.Write("Enter your input here: ");
string userinput = Console.ReadLine();
Just change Console.WriteLine to Console.Write.
Use Console.Write() instead of Console.WriteLine().
I think that's what you mean anyway, the question isn't very clear.
I think you're asking if it's possible to read both height and weight at the same time:
// C equivalent
printf ("Enter height (cm) and weight (kg): ");
scanf ("%d %d\n", &h, &w);
Yes, there are several alternatives.
Arguably the easiest is use Console.ReadLine() (like you're doing) and parse the string.
You can also try multiple "Console.Read()" (one for each argument).
Related
{
Console.ForegroundColor= ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("Please enter your name and I will tell you how many letters your name has!");
string name = Console.ReadLine();
Count(name);
Console.WriteLine("Now tell me two numbers and I will multiply them!");
Console.Read();
try
{
Multiply();
}
catch (FormatException)
{
Console.WriteLine("You must enter a number!");
}
}
public static void Count(string name)
{
Console.WriteLine("Your name has {0} letters!", name.Length);
}
public static void Multiply()
{
string firstNum = Console.ReadLine();
string secondNum = Console.ReadLine();
int num = Int32.Parse(firstNum);
int num1 = Int32.Parse(secondNum);
int result = num * num1;
Console.WriteLine("The result is {0}", result);
}
Im a beginner and Im learning about methods so I made this simple code where the user should enter two numbers and I should multiply them, the problem is, whenever I enter two random numbers, I am getting some completely different numbers back no matter if i want to add them, multiply them or something third.
I cannot figure out why the "num1 * num2;" is not giving me a correct number. E.G. 54*19 should give me 1026, but instead its giving me -15.
you need to comment on the Console.Read(); line. this is the main cause.
I have run your code by commenting on the above line and it works as expected for me
Also, you need to handle the scenarios when the user can enter a non-integer input, so you could use int.TryParse for the same.
Also, try to handle the scenario where the integer value is very large and the multiplication of two numbers exceeds the integer max value.
I have a menu with option.
Option 1: BMI caculator (option 1/case 1)
When entering the details in BMI calculator such as Height in Meters I am trying to get it to loop back and print an error message and ask again if the height that the user entered isn't a int (meters) for example if the user inputs a string say "M" it will not work and loops back to the initial question prompting for input IE: 2.1. I'm trying to use IF ELSE inside the switch/case. You can see in height section I can use goto case 1 to loop it but does not work for weight ( because that will go back to the beginning of case 1 and user would need to enter height again), Whatever the outcome of weight I need to keep the result of Height prior to weight so as to perform the final calculation BMI = . Sorry if this isn't clear, I'm really new and really stuck.
switch (optionsIn)
case 1:
{
Console.Clear();
Console.WriteLine("What is your height in meters");
double heightMax = 0.00;
string heightMeters = Console.ReadLine();
double.TryParse(heightMeters, out double heightM);
if (heightMax < heightM)
{
Console.Clear(); // nothing needs to run here , just clear to look better and move to collection of weight.
}
else
{
Console.Clear();
Console.WriteLine("Incorrect option try again");
Console.WriteLine("press enter to try again");
Console.ReadKey();
goto case 1; // better way to do it rather than goto case 1?
}
Console.WriteLine("Enter weight in Kgs"); // need to start here if incorrect input from user
double kgs = 00.00;
string weight = Console.ReadLine();
double.TryParse(weight, out double weightKgs);
if (kgs < weightKgs)
{
Console.Clear(); // nothing needs to run here , just clear console to look neat and move to calculating and printing BMI
}
else
{
Console.WriteLine("Incorrect option try again"); // cannot get to loop back to Enter weight
Console.WriteLine("press enter to return");
Console.ReadKey();
break;
}
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is " + bmi);
Console.WriteLine("press any key to exit");
Console.ReadKey();
break;
}
I suggest method extraction:
public static double ReadDouble(string title, Func<double, bool> validation) {
// Keep Asking User until correct value is provided
while (true) {
// Show title if we have it
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (!double.TryParse(Console.ReadLine(), out double result))
// Not a double value at all; say, "bla-bla-bla"
Console.WriteLine("Syntax error. Please, try again.");
else if (validation != null && !validation(result))
// Not a valid double value, say, 123456.89 kg weight
Console.WriteLine("Not a valid value. Please, try again.");
else
return result;
}
}
then you can easily use it within switch \ case:
double heightM = ReadDouble("What is your height in meters", m => m > 0.3 && m < 3.0);
double weightKgs = ReadDouble("Enter weight in Kgs", m => m > 0.7 && m < 700.0);
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is {bmi:F1}");
Instead of using goto - which is considered bad practice and is not all that much readable, try using a while or do/while loop instead.
Something like:
string input;
double heightMax = 0.0;
do {
input = Console.ReadLine();
double.TryParse(input, out double heightM);
Console.Clear();
} while (heightMax >= heightM);
Also, consider using functions for loading the data. Maybe you can think of some way of generalizing so that you can have only one function that you can reuse for all the stuff you need to load.
Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails
I'm trying to learn the basics to c# coding (or any code for that matter). I'm not understanding how to take user input and put it into a string that I can later use as an integer. I thought I could write it like
string baseOfTriange = int.Parse(Console.ReadLine));
but it's not working. I've also tried float thinking maybe that was it, however, I'm just lost on the concept. This is what I have so far, I just can't figure out how to convert a string to an int. Thanks for any help.
static void Main(string[] args)
{
// area of a triangle = base(height)/2
Console.WriteLine("Welcome, enter your triangle dimensions. ");
Console.WriteLine();
Console.Write("What is the base of the triangle? ");
string baseOfTriangle = int.Parse(Console.ReadLine());
Console.WriteLine("You answered, " + baseOfTriangle + ". ");
Console.Write("What is your height of the triangle? ");
string heightOfTriangle = int.Parse(Console.ReadLine());
Console.WriteLine("You answered, " + heightOfTriangle + ". ");
Console.WriteLine("The area of the triangle is " + (baseOfTriangle * heightOfTriangle / 2));
Console.ReadLine();
}
I'll assume you're getting a compile time error because of the following line:
string baseOfTriangle = int.Parse(Console.ReadLine());
The return type of int.Parse is int but your trying to assign it to a variable of type string. Change the type of baseOfTriangle and heightOfTriangle to int and that will solve your problem.
int baseOfTriangle = int.Parse(Console.ReadLine());
^^^
Also, you probably want a floating point answer. Otherwise 1*1/2 will give you an answer of 0. Change it to baseOfTriangle * heightOfTriangle / 2.0. Or better yet use double and double.Parse.
Take a look at the C# Programming Guide: How to: Convert a String to a Number:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Also look at the TryParse methods for most built-in number types for c#. For example, int32.TryParse():
http://msdn.microsoft.com/en-us/library/system.int32.tryparse(v=vs.110).aspx
static void Main(string[] args)
{
Console.Write("What is the base of the triangle? ");
int baseOfTriangle = int.Parse(Console.ReadLine());
Console.Write("What is your height of the triangle? ");
int heightOfTriangle = int.Parse(Console.ReadLine());
Console.WriteLine("The area of the triangle is {0}", (baseOfTriangle * heightOfTriangle) / 2);
Console.ReadLine();
}
The usual method to convert to int is with Convert.ToInt32()
using System;
namespace area
{
class Program
{
static void Main(string[] args)
{
double basse;
double height;
Console.WriteLine("Enter your base length: ");
basse = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( "Enter the height: ");
height = Convert.ToDouble(Console.ReadLine());
double area = Program.triangleArea(basse, height);
Console.WriteLine("Your area is {0:f3}", area);
Console.ReadLine();
double pryrmid = Program.pyramidVolume( triangleArea);
Console.WriteLine(" Pyramid Volume is {0:f3}" , pryrmid);
}
public static double triangleArea(double basse, double height)
{
return (0.5 * basse) * height;
}
public static double pyramidVolume (double triangleArea)
{
return (1/3) * triangleArea;
}
}
}
I'm trying the calculate the volume of a pryamid using the methods ive defined.
I keep getting the error
Argument '1': cannot convert from 'method group' to 'double' (CS1503)
- \vmware-host\Shared Folders\Documents\SharpDevelop Projects\WS_6_D\WS_6_D\Program.cs:28,57
and
The best overloaded method match for
'area.Program.pyramidVolume(double)' has some invalid arguments
(CS1502) - \vmware-host\Shared Folders\Documents\SharpDevelop
Projects\WS_6_D\WS_6_D\Program.cs:28,34
I was wondering if someone could help me get on the right track.
The problem is that triangleArea in
double pryrmid = Program.pyramidVolume( triangleArea); is not a variable, hence it points to the static method.
Try double pryrmid = Program.pyramidVolume( area); instead.
The compiler is expecting something it can evaluate to a double, but you supply the name of a function (triangleArea).
Instead, you probably want to pass the area you calculated previously.
I think you meant to say
double pryrmid = Program.pyramidVolume(area);
instead of
double pryrmid = Program.pyramidVolume( triangleArea);
triangleArea is your method, you used area as your result value.