I need help instantiating multiple objects from a single method & class - c#

C# HOMEWORK QUESTION: I am creating a console application that prompts for two integers, prompts for which math operation to perform, and returns the results. I was able to get it to work with my two operands hardcoded, and now I'm trying to instantiate two separate objects through user input instead of a hardcoded variable. I've stripped it down to the barebones code that I'm having issues with, and I suspect the problem has something to do with the way I'm creating two objects from the same method...but I'm not sure what.
Here's my main class...
public class MainModule
{
public static void Main(string[] args)
{
// get Operands
Console.WriteLine("You Will Be Entering Two Integers.\n");
//
MathUI myOperand1 = new MathUI();
int op1 = myOperand1.EnterInteger();
//
MathUI myOperand2 = new MathUI();
int op2 = myOperand2.EnterInteger();
Console.WriteLine("You chose {0} and {1}.", (int)op1, (int)op2);
Console.ReadLine();
}
}
...and the MathUI class that accepts inputs.
public class MathUI
{
public int EnterInteger()
{
Console.Write("Enter an integer: ");
int enteredInteger = Console.Read();
return (enteredInteger);
}
}
When I execute the program, I get a prompt for an integer. I enter, for instance, 3, here's my output.
You Will Be Entering Two Integers.
Enter an integer: 3
Enter an integer: You chose 51 and 13.
Math demo completed
Press <enter> to quit
When I press enter after entering the first integer, I automatically get a second integer; and when I try to output the integer values, they don't match my input.
What's going on here? Is there something wrong with the way that I'm instantiating MathUI and my two operands? Do I only need to instantiate one instance of MathUI then declare both variables under that one instance? I'm also not sure why the integer output does not match my input. All the variables are cast as int, so I should have int all the way through, right? I tried casting these as integers--(int)op1--just in case op1 was held in some internal form...but don't know what's going on there.
What am I missing?

you need to make the Console.Read a Console.ReadLine as readline is triggered by the return key.
public class MathUI
{
public int EnterInteger()
{
Console.Write("Enter an integer: ");
int enteredInteger = Convert.ToInt32(Console.ReadLine());
return (enteredInteger);
}
}

Problem is that you are using Console.Read method which returns a value after any key has been pressed. Also, result it returns is ASCII value of key pressed. In your case, you pressed 3 which has ordinal (ASCII) value of 51 in decimal system and then ENTER which has value 13. If you look at MSDN documentation, Console.Read returns an integer.
To read value user entered as a string, use Console.ReadLine method.
If you really need to read in key by key, you can use Convert.ToChar, and then ToString method to get entered key as string. Like so:
string key = Convert.ToChar(Console.ReadLine()).ToString();
Or you can use following code to read actual operand
int intOperand;
if (!int.TryParse(Console.ReadLine(), out intOperant))
Console.WriteLine("You pressed non-numeric key");

Use Console.ReadLine instead of Console.Read. With Console.Read, the return character is being passed as input to the second Read call.
Also note that the int that is returned by Console.Read is not parsing a numeric number, it is giving you the Unicode character value of the entered char. This is why you are getting the "wrong" numbers.
You need to use Console.ReadLine and parse the string result like so:
public class MathUI
{
public int EnterInteger()
{
Console.Write("Enter an integer: ");
int enteredInteger = int.Parse(Console.ReadLine());
return (enteredInteger);
}
}
A couple other notes for your consideration:
There's no need to cast the values in the Console.WriteLine call.
You can make the MathUI class and EnterInteger method static.

Related

Why does this code not work when I try to convert it

This is only a small piece of the code I'm trying to make work. The original code I wrote works but I want to make sure when the user inputs a number it is in fact a number.
Console.WriteLine("Give the number of A");
A =Convert.ToDouble( Console.ReadLine());
if (char.IsNumber(Convert.ToDouble(A)) == correct)
{
Console.WriteLine(Convert.ToDouble( A * A));
}
else
{
Console.WriteLine("Incorrecrt input");
}
The Console.WriteLine(Convert.ToDouble(A*A)); I only wrote to see if that will work and it doesn't. After the user inputs only a number I must use it in another equation for a final answer. The user must input 3 numbers.
For me, you should check is the input is a number that you can convert to double before converting it.
Console.WriteLine("Give the number of A");
var a = Console.ReadLine();
double number;
if (double.TryParse(a, out number))//double.TryParse takes a parameter and tries to convert it to double. If the convertion is successfull, sets the out parameter as result and returns true. If not, returns false. And you can use with other types like int.Tryparse(param, out outParam);
{
A = number;
}
else
{
//Not a number, show a message etc...
{
If you break this down:
A =Convert.ToDouble( Console.ReadLine());
if (char.IsNumber(Convert.ToDouble(A)) == correct)
{
}
What you're basically doing is:
Double A = Convert.ToDouble(Console.ReadLine());
Double dbl = Convert.ToDouble(A);
Boolean bl = char.IsNumber(dbl);
if (bl== correct)
{
}
So there's multiple things wrong here.
Firstly, you're trying to convert the user input without any sort of guarantee of success, so if someone typed "A" instead of a number it will throw an exception.
You should use TryParse and then if it's a valid conversion proceed.
Secondly, you're checking if a Double is a char that can be converted to a number. Obviously not because it's already a Double.
Thirdly, you're checking if a Boolean is equal to some variable called correct (which you haven't provided the definition of) so it's not clear if this is a valid comparsion.
EDIT:
This is what I would do:
bool validInput = false;
do
{
Console.WriteLine("Give the number of A");
string userInput = Console.ReadLine();
if (double.TryParse(userInput, out double result))
{
validInput = true;
Console.WriteLine(result * result);
Console.ReadLine();
}
else
{
Console.WriteLine("Invalid input. Please type a number.");
}
} while (!validInput);

How to print an error message if input is not a number?

I wonder how to print an error message if user's input is not a number.
Console.WriteLine("Water amount in ml:");
int waterAmount = Convert.ToInt32(Console.ReadLine());
Most answers from other posts don't work, because waterAmount is a Int32, not a string.
Also, sorry if my English is weak, it's not my native language
I see you did not accept the other answers. Maybe you want to make the user try again after he did not input a number. You can do that with a while loop, or easier, using the goto keyword. You simply put a tag before everything is happening (in my case, waterAmountInput), and if the input was not a number, you write your error message and go to the beginning again. Here is the code:
int waterAmount;
waterAmountInput:
Console.Write("Water amount in ml: ");
try
{
waterAmount = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("The water amount needs to be a number!");
goto waterAmountInput;
}
You can try using C#'s TryParse() functions.
These attempt to convert values, but if they fail they return false rather than erroring.
I would suggest trying this code:
Console.WriteLine("Water amount in ml:");
string input = Console.ReadLine();
if (Int32.TryParse(input, out var value))
// Do something here. The converted int is stored in "value".
else
Console.WriteLine("Please enter a number");
You should use TryParse function:
Console.WriteLine("Water amount in ml:");
int waterAmount = 0;
if (int.TryParse(Console.ReadLine(), waterAmount)) {
} else {
Console.WriteLine("Error Message");
}
You will need to use TryParse before presuming it to be a number.
After Console.WriteLine you can capture and parse the input and if TryParse returns false, you can display an error message.
Note: if the conversion succeeds the numeric value is available in the waterAmt local variable.
Console.WriteLine("Water amount in ml:");
var input = Console.ReadLine();
if(!int.TryParse(input, out int waterAmt))
Console.WriteLine("Input is not a number");

C# help, overloading a method

I have one last thing to add to my assignment before im finished.
This is a part of my code:
static decimal FahrToCels(int fahrenheit) //Metod för konvertering av Fahrenheit(F) till Celsius(C)
{
decimal celsius = (decimal)((fahrenheit - 32) * 5) / 9; // Matematisk uträkning för F till C.
return Math.Round (celsius, 1); //Lagrar ett decimal tal avrundat till 1 decimal och lagrar i celsius
}
static void Main(string[] args)
{
Console.Write("Vänligen ange temperatur till bastun och tryck enter: "); //skriver ut meddelande
do
int fahr = int.Parse(Console.ReadLine()); // Omvandlar string och lagrar användarens inmatning i en int fahrenheit
decimal celsius = FahrToCels(fahr); // Metoden FahrToCels konverterar inmatad temperatur till celsius och lagrar i decimal celsius
As can be seen, ive created a method, that is later used after the user is told to enter degrees in fahrenheit. The method converts the entered number to celsius.
Now the last thing im told to do is by overloading the method, make it possible for the user to enter zero(0) and by doing that randomly generate a number before that number goes into the fahrenheit to celsius converting method. Im guessing the generated numbet has to be like between 140-195 because the user needs to enter zero until the generated number equals to 73-77 after converting to celsius!
I know how to generate a random number, and i think i understand what overloading does, but im totally lost on how to do this one...
An idea would be to create a function under (or over) the method inside the class that takes no arguments. Nothing else special is required. When you want to call FahrToCels(), you have the option to call either method based on the type and quantity of the arguments.
static decimal FahrToCels ()
{
// Your code here
}
Create a new method like this
static decimal FahrToCels(string value) //note value is of type 'string'
{
//your implementation goes here, check if value is 'zero'
}
This solves your requirement to use method overloading, event though I find it a bit odd.
Apart from other possible concerns: Overloading a method has nothing to do with specific parameter values (unless you are using different types, e.g. short, int, long). In your case: "if the parameter value is 0 then return a random number" is not something solvable by overloading.
Now after reading your comment on the question; you could create a method that doesn't take any parameters static decimal FahrToCels() and call that in case you read a 0 from the input. This new method would then generate a random value and convert that.
Personal opinion: I'm not gonna comment on how reasonable that assignment is. The more standard case would be to use an if statement to decide if the input was 0 and if so generate a random value and pass that to the method you already have. But I might be missing something here.

My code works, but I don't fully understand how

using System;
namespace SimpleweightConversion
{
public class PoundstoKilos
{
public static void Main()
{
double pounds = 0.0;
Console.Write("How many pounds? ");
double.TryParse(Console.ReadLine(), out pounds);
double kilograms = pounds * 0.453592;
Console.WriteLine("{0} pounds is equal to {1} kilograms", pounds,
kilograms);
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
I'm trying to learn C# and I created this code to convert from pounds to kilograms, I added the tryparse bit to avoid an error if the user throws something other than numbers at the program, and it works!.The only problem I have is it doesn't clearly show when does it assign the user's input to the pounds variable, because at the start, the value of the pounds variable is 0.0, but at some point, the value provided by the user is assigned to the pounds variable, or at least that's what I think is happening.
From the Microsoft Docs, the syntax for TryParse() is:
public static bool TryParse(
string s,
out double result
)
This means that if the string s is numeric, its parsed value is immediately assigned to the variable result.
In your code, you have the line double.TryParse(Console.ReadLine(), out pounds);
In this case, the input from the console is parsed to a double, and assigned to pounds if possible.
The user's input is assigned to the pounds variable within the TryParse() method.
The out modifier indicates that the argument is being passed by reference - which means that any changes to the argument (in this case, pounds) that occur within the method call will be applied to the actual variable.
It is get assigned when u take user's input using Console. ReadLine() method.
"I.e. double.TryParse(Console.ReadLine(), out pounds);"
User's input is extracted into pounds variable.
The other answers have explained your error. I thought I'd just show you how you should write your code to make it easier to understand:
public class PoundsToKilos
{
public static void Main()
{
double pounds = 0.0;
Console.Write("How many pounds? ");
if (double.TryParse(Console.ReadLine(), out pounds))
{
//`pounds` has been assigned a value
double kilograms = pounds * 0.453592;
Console.WriteLine("{0} pounds is equal to {1} kilograms", pounds, kilograms);
}
else
{
//`pounds` has NOT been assigned a value
Console.WriteLine("You didn't enter a valid number.");
}
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}

C# regular expressions for integers

I am trying to create a static method that validates if input is actually a number or not and I want to do it with a regex. I get an error "cannot convert int to string" when I try to do it, but it's my understanding that integers also can be compared using regex.
This is my static method so far.
public static void validatenumber(int number)
{
Regex regex = new Regex("^[0-9]+$");
if (regex.IsMatch(number))
{
Console.WriteLine("The input is a number");
}
else
{
Console.WriteLine("The input is not a number");
}
}
And this is the input that I am trying to validate, which is in the Main method.
Console.WriteLine("Please enter a number");
int number= Convert.ToInt32(Console.ReadLine());
validatenumber(number);
My variable number in my Main method needs to be an int, I cannot change that.
Your problem is not the Regex error you are getting, but the fact that you are trying to validate an int as a number. There is no sense in this validation, since the compiler will never allow an int variable to hold something else except a number.
It would make sense if yot method was receiving a string as a parameter:
validatenumber(string number)
In which case, you would not get this error, since Regex works with strings.
An issue with you code is found here, which leads to your regex (as you have to perform regex on a string not an int).
Console.WriteLine("Please enter a number");
int number= Convert.ToInt32(Console.ReadLine()); // <--- Here!
validatenumber(number);
Console.ReadLine() will return a string. So your code will throw an error or give you an unexpected result when you try to do Convert.ToInt32() on it.
You will need to change your code to look like the following:
static void Main(string[] args)
{
...
Console.WriteLine("Please enter a number");
string numberString = Console.ReadLine();
int number = ConvertAndValidateNumber(number); // we are now going to return an int
...
}
and then change the the validatenumber method to return the int type using the int.TryParse() method, which is much easier to read.
public static int ConvertAndValidateNumber(string numberString)
{
int.TryParse(numberString, out int number);
return number;
}
If you REALLY want to use RegEx (which makes sense in some very special cases), then you can change the above method to:
public static int ConvertAndValidateNumberUsingRegEx(string numberString)
{
int number;
//
// put your RegEx here...
//
// and don't forget to assign the converted string value into the number
number = (your converted string);
// return it
return number;
}
You also may want to validate that your regex is valid by testing it here http://regexr.com/

Categories