The else statement, "Weight must be greater than 0" is working, but if I were to enter a letter into my PackageWeight.Text textbox, the else statement won't show.
if (decimal.TryParse(PackageWeight.Text, out weight))
{
if (weight > 0)
{
weightcost = pound * weight;
Weight.Text = weightcost.ToString("c");
}
else
{
MessageBox.Show("Weight must be greater than 0.");
}
}
else
{
MessageBox.Show("Invalid input for weight.");
}
static void Main(string[] args)
{
Parse("1");
Parse("-1");
Parse("DDD");
}
private static void Parse(string x)
{
if (decimal.TryParse(x, out decimal weight))
{
if (weight > 0)
{
var weightcost = 2 * weight;
Console.WriteLine(weightcost.ToString("c"));
}
else
{
Console.WriteLine("Weight must be greater than 0.");
}
}
else
{
Console.WriteLine("Invalid input for weight.");
}
}
produces the correct output:
Related
Im trying to create a report card class and return a letter grade to main. I used a class constructor for the report card as the actual report card must be a class. In the event an invalid value is entered it will return an argument exception an prompt the user to try again. Here is my code:
using System;
using static System.Console;
class StudentGradeDemo
{
static void Main()
{
char lettergrade = new ReportCard();
}
class StudentGrades
{
public string studentName;
public double midtermGrade;
public double finalExamGrade;
public char letterGrade;
public char ReportCard(string studentName, double midtermGrade, double finalExamGrade)
{
char[] letterGrade = { 'A', 'B', 'C', 'D', 'F' };
Console.WriteLine("Enter midterm grade");
midtermGrade = Convert.ToInt32(Console.ReadLine());
if(midtermGrade >= 0 && midtermGrade <= 100)
{
Console.WriteLine("Enter final exam grade");
finalExamGrade = Convert.ToInt32(Console.ReadLine());
if (finalExamGrade >= 0 && midtermGrade <= 100)
{
double gradeAverage = ((midtermGrade + finalExamGrade) / 2);
if(gradeAverage >= 90 && gradeAverage <= 100)
{
return letterGrade[0];
}
else if(gradeAverage >= 80 && gradeAverage <= 90)
{
return letterGrade[1];
}
else if(gradeAverage >= 70 && gradeAverage <= 80)
{
return letterGrade[2];
}
else if(gradeAverage >= 60 && gradeAverage <= 70)
{
return letterGrade[3];
}
else if(gradeAverage < 60)
{
return letterGrade[4];
}
}
else
{
try
{
throw new System.ArgumentException();
}
catch (ArgumentException)
{
Console.WriteLine("Grades must be between 0 - 100");
return letterGrade[0];
}
}
}
else
{
try
{
throw new System.ArgumentException();
}
catch (ArgumentException)
{
Console.WriteLine("Grades must be between 0 - 100");
return letterGrade[0];
}
}
return letterGrade[0];
}
}
}
The error that returns is: Error CS0246 The type or namespace name 'ReportCard' could not be found (are you missing a using directive or an assembly reference?)
This first thing you need to do is create an instance of the StudentGrades class. This will allow you to access the ReportCard method, as it's a method of the class. (see #1). https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods
Next, if you look at the ReportCard method it takes 3 parameters: studentName, midtermGrade, finalGrade. These values MUST be passed into the method when you call it (see #2). https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
static void Main()
{
var studentGrades = new StudentGrades(); // #1
Console.WriteLine("Enter student name");
var studentName = Console.ReadLine();
Console.WriteLine("Enter midterm grade");
var midtermGrade = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter final exam grade");
var finalExamGrade = Convert.ToDouble(Console.ReadLine());
var lettergrade = studentGrades.ReportCard(studentName, midtermGrade, finalExamGrade); // #2
Console.WriteLine($"{studentName}'s grade is an {lettergrade}");
}
Update: If you want to read input from the user, read in each line and assign to appropriate variable to pass in. I took this code from your ReportCard method, so you need to make sure to remove it from there. Also, you should be doing the appropriate type checking and handling for midterm and finalExamGrade. I'll leave that to you.
This is how to solve your problem:
class Program
{
static void Main(string[] args)
{
char lettergrade = StudentGrades.ReportCard();
}
}
public static class StudentGrades
{
public static char ReportCard()
{
char[] letterGrade = { 'A', 'B', 'C', 'D', 'F' };
Console.WriteLine("Enter midterm grade");
double midtermGrade = Convert.ToInt32(Console.ReadLine());
if (midtermGrade >= 0 && midtermGrade <= 100)
{
Console.WriteLine("Enter final exam grade");
double finalExamGrade = Convert.ToInt32(Console.ReadLine());
if (finalExamGrade >= 0 && midtermGrade <= 100)
{
double gradeAverage = ((midtermGrade + finalExamGrade) / 2);
if (gradeAverage >= 90 && gradeAverage <= 100)
{
return letterGrade[0];
}
else if (gradeAverage >= 80 && gradeAverage <= 90)
{
return letterGrade[1];
}
else if (gradeAverage >= 70 && gradeAverage <= 80)
{
return letterGrade[2];
}
else if (gradeAverage >= 60 && gradeAverage <= 70)
{
return letterGrade[3];
}
else if (gradeAverage < 60)
{
return letterGrade[4];
}
}
else
{
try
{
throw new System.ArgumentException();
}
catch (ArgumentException)
{
Console.WriteLine("Grades must be between 0 - 100");
return letterGrade[0];
}
}
}
else
{
try
{
throw new System.ArgumentException();
}
catch (ArgumentException)
{
Console.WriteLine("Grades must be between 0 - 100");
return letterGrade[0];
}
}
return letterGrade[0];
}
}
For better understanding I will first post my Program Class.
Program.cs
namespace BeginnersGuidToLifting
{
class Program
{
public static readonly int width = 85;
public static readonly int height = 35;
public static readonly User user = new User();
public static readonly Goal goal = new Goal();
public static Calories calories = new Calories();
public static Nutrition nutrition = new Nutrition();
public static Menu menu = new Menu();
static void InitUser()
{
Console.WriteLine("\n### About You ###\n");
user.Name = Question.AskString("Name: ");
user.Age = Question.AskInt("Age: ");
user.Gender = Question.AskString("Gender(m/f): ");
user.Height = Question.AskInt("Height(cm): ");
user.Weight = Question.AskInt("Weight(kg): ");
}
static void InitGoals()
{
Console.WriteLine("\n### What are your Goals ### \n");
goal.GainWeight();
goal.LoseWeight();
goal.GetStronger();
goal.GetLeaner();
goal.StayFit();
goal.Hypertrophy();
Console.Write("Answer: ");
var input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.D1:
goal.GoalStatusGainWeight = true;
goal.GoalMessage = "Your Goal is to Gain Weight";
break;
case ConsoleKey.D2:
goal.GoalStatusLoseWeight = true;
goal.GoalMessage = "Your Goal is to Lose weight";
break;
case ConsoleKey.D3:
goal.GoalStatusGetStronger = true;
goal.GoalMessage = "Your Goal is to get Stronger";
break;
case ConsoleKey.D4:
goal.GoalStatusGetLeaner = true;
goal.GoalMessage = "Your Goal is to get Leaner";
break;
case ConsoleKey.D5:
goal.GoalStatusStayFit = true;
goal.GoalMessage = "Your Goal is to Stay Fit";
break;
case ConsoleKey.D6:
goal.GoalStatusHypertrophy = true;
goal.GoalMessage = "Your Goal is Hypertrophy";
break;
default:
Console.WriteLine("Error");
break;
}
}
static void InitMenu()
{
menu.ShowMenu();
menu.Discalmer = false;
//menu.Disclamer();
}
static void BmiResult()
{
var bodyType = user.GetBodyType();
if (bodyType == User.BodyType.ReallyUnderweight)
{
Console.WriteLine("Really Underweigt");
}
else if (bodyType == User.BodyType.Underweight)
{
Console.WriteLine("Underweight");
}
else if (bodyType == User.BodyType.CloseToUnderwight)
{
Console.WriteLine("Close to Underweight");
}
else if (bodyType == User.BodyType.Healthy)
{
Console.WriteLine("at a Healthy Weight");
}
else if (bodyType == User.BodyType.Overweight)
{
Console.WriteLine("Overweight");
}
else if (bodyType == User.BodyType.Obese)
{
Console.WriteLine("Obese");
}
else if (bodyType == User.BodyType.SeverlyObese)
{
Console.WriteLine("Serverley Obese");
}
else if (bodyType == User.BodyType.MorbidlyObese)
{
Console.WriteLine("Morbidly Obese");
}
}
static void Main(string[] args)
{
Console.Title = "Beginers Guide To Lifting";
Console.SetWindowSize(width, height);
Console.SetBufferSize(width, height);
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
//Status So Far
Console.WriteLine("\n### Your Stats ### \n");
Console.WriteLine("Name: {0} \nAge: {1} \nHeight: {2} \nWeight: {3}", user.Name, user.Age, user.Height, user.Weight);
Console.WriteLine("Goal: {0}", goal.GoalMessage);
BmiResult();
Console.Write("\nContinue(y/n) to The Programm?: ");
if (Console.ReadLine() == "y")
{
Console.Clear();
}
//Gain Weight Goal
//Introduce 5x5
var exercise = new FiveByFive();
exercise.printIntroduction();
//Show Exercises
exercise.printWorkoutWeek1();
exercise.printWorkoutWeek2();
//Show Nutrition
if (goal.GoalStatusGainWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.GainCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.GainCaloriesFemale(user);
break;
}
}
//Lose Weight
if (goal.GoalStatusLoseWeight == true)
{
switch (user.Gender)
{
case "male":
case "m":
case "Male":
calories.LoseCaloriesMale(user);
break;
case "female":
case "f":
case "Female":
calories.LoseCaloriesFemale(user);
break;
}
}
}
}
}
The Problem is in my Main Method.
InitMenu();
var userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.D1:
InitUser();
InitGoals();
break;
case ConsoleKey.D2:
Console.WriteLine("Press 2");
break;
default:
Console.WriteLine("Why y no work");
break;
}
When I press one, it should happen what it shows.
Init User and Init User Goals.
How ever when i press 2 it brings me to the User.cs class,
where i am doing the Math for the Users BMI.
I dont really understand why it would do that when pressing 2, because all i want to display is "Press 2" Or later to be added A disclamer.
The Exeption
System.DivideByZeroException: 'Attempted to divide by zero.'
Is thrown because it tries to divde 0 with 0 and that is because there is no input from the user yet. Because all i would like to do by pressing 2 is display another window with some text. And that is is.
I really dont understand why it jumps to the User class.
Here is User.cs for better understanding.
namespace BeginnersGuidToLifting
{
class User
{
public enum BodyType
{
ReallyUnderweight,
Underweight,
CloseToUnderwight,
Healthy,
Overweight,
Obese,
SeverlyObese,
MorbidlyObese
}
public string Name;
//private string _gender;
public string Gender;
private int _weight;
private int _height;
private int _age;
public int Age
{
get => _age;
set
{
if (value >= 0)
{
_age = value;
}
}
}
public int Weight
{
get => _weight;
set
{
if (value >= 0)
{
_weight = value;
}
}
}
public int Height
{
get => _height;
set
{
if (value >= 0)
{
_height = value;
}
}
}
//TODO
//public string Gender
//{
// get => _gender;
// set
// {
// if (value == "female" || value == "f" || value == "male" || value == "m" )
// _gender = value;
// else
// {
// Console.WriteLine("Value Wrong");
// }
// }
//}
public int GetBmi()
{
Console.WriteLine("Weight:"+Weight);
//var bmi = Math.Round((Weight / Math.Pow(Height, 2)) * 10000);
int bmi = Weight / (Height * Height) * 10000;
Console.WriteLine("Your Body Mass Index: " + bmi);
Console.Write("That Means That you are: ");
return bmi;
}
public BodyType GetBodyType()
{
int bmi = GetBmi();
if (bmi < 16)
return BodyType.ReallyUnderweight;
else if (bmi >= 16 && bmi <= 17)
return BodyType.Underweight;
else if (bmi >= 17 && bmi <= 18.5)
return BodyType.CloseToUnderwight;
else if (bmi >= 18.5 && bmi <= 25)
return BodyType.Healthy;
else if (bmi >= 25 && bmi <= 30)
return BodyType.Overweight;
else if (bmi >= 30 && bmi <= 35)
return BodyType.Obese;
else if (bmi >= 35 && bmi <= 40)
return BodyType.SeverlyObese;
return BodyType.MorbidlyObese;
}
}
}
Summary
A switch command calls 2 actions when number 1 and number 2 is
pressed on the keyboard.
When pressing 1 everything works fine and
does what it should.
When pressing 2 it tries to do the math for
something there is no input yet, Because input is only asked when
pressing 1.
Thank you in advance for taking the time to read this.
Any input is welcome. I hope everything is clear to understand.
After you press '2' and it exits the switch, it calls BmiResult(), which calls methods in the user class.
BmiResult() calls user.GetBodyType(), which calls GetBmi() on the user class. This is where your calculation happens, but since you didn't set any of the values on the user, every thing defaults to zero. Which means you are doing this:
int bmi = 0 / (0 * 0) * 10000;
Order of operations means it does this:
int bmi = (0 / 0) * 10000;
because division and multiplication are executed within parantheses first, then left to right.
However, multiplying zero by anything would still be zero, so you need to check if the divisor would be zero before doing the calculation, or wrap the code in a try/catch and handle it.
I want to input a numerical value in a text box ranging from 0 to 100, then press a button and display the corresponding grade. So far, I have this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnIF_Click(object sender, EventArgs e)
{
int[] i = new int[1];
txtNumK.Text = i[0].ToString();
{
Console.WriteLine("Please enter test " + i);
bool result = int.TryParse(Console.ReadLine(), out i[0]);
if (!result)
{
Console.WriteLine("This program only accept numbers.");
}
if (i[0] >= 90)
{
Console.WriteLine("note is A");
}
if (i[0] >= 80)
{
Console.WriteLine("note is B");
}
if (i[0] >= 70)
{
Console.WriteLine("note is C");
}
if (i[0] >= 60)
{
Console.WriteLine("note is D");
}
if (i[0] >= 0)
{
Console.WriteLine("note is F");
}
else if (i[0] > 0 || i[0] < 100)
{
Console.WriteLine("I'm sorry, the number MUST be between 0 and 100");
}
Console.WriteLine("Your result is:" + i[0]);
}
}
private void txtNumK_TextChanged(object sender, EventArgs e)
{
}
}
}
Every time I input a number in the text box, the value within it is turned back into a 0.
You have your assignment backwards. You want:
i[0] = Int32.parse(txtNumk.text);
I am trying to make a windows form application that allows users to convert currency. I currently am working on making sure the value passed to the converter is only a positive integer. I have a message that pops up whenever anything other than a positive integer is entered, but when i enter something like "a" it keeps popping up and wont let me enter any other values.
public int USCurren(int value)
{
bool MessageShown;
string input = textBox1.Text;
while(true)
{
if (int.TryParse(input, out value))
{
if (MessageShown = false && value <= 0)
{
MessageShown = true;
MessageBox.Show("Please Input A Positive Integer");
textBox1.Clear();
}
else
return value;
MessageShown = false;
}
else
{
MessageShown = true;
MessageBox.Show("Please Input A Positive Integer");
textBox1.Clear();
}
}
You can do it like this way,
public int USCurren()
{
string input = textBox1.Text;
int value = -1;
try
{
if (int.TryParse(input, out value) && value > 0)
{
//Write your code here to convert the currency;
return value;
}
else
{
MessageBox.Show("Please Input A Positive Integer");
textBox1.Clear();
value = -1;
}
}
catch (Exception ex)
{
//Show exception here
}
return value;
}
I have written my codes and i want to validate it in such a way thet it will only allow intergers to be inputed and not alphabets. Here is the code, please I will love you to help me. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace minimum
{
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
if (a < b)
{
if (a < c)
{
Console.WriteLine(a + "is the minimum number");
}
}
if (b < a)
{
if (b < c)
{
Console.WriteLine(b + "is the minimum number");
}
}
if (c < a)
{
if (c < b)
{
Console.WriteLine(c + "is the minimum number");
}
}
Console.ReadLine();
}
}
}
You should test if it's an int instead of converting in right away.
Try something like :
string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
// this is an int
// do you minimum number check here
}
else
{
// this is not an int
}
Simply call Readline() and loop with Int.TryParse until the user inputs a valid number :)
int X;
String Result = Console.ReadLine();
while(!Int32.TryParse(Result, out X))
{
Console.WriteLine("Not a valid number, try again.");
Result = Console.ReadLine();
}
Hope that helps
To get the console to filter out alphabetical keystrokes you have to take over input parsing. The Console.ReadKey() method is fundamental to this, it lets you sniff the pressed key. Here's a sample implementation:
static string ReadNumber() {
var buf = new StringBuilder();
for (; ; ) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
return buf.ToString() ;
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
buf.Remove(buf.Length-1, 1);
Console.Write("\b \b");
}
else if ("0123456789.-".Contains(key.KeyChar)) {
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else {
Console.Beep();
}
}
}
You could add, say, Decimal.TryParse() in the if() statement that detects the Enter key to verify that the entered string is still a valid number. That way you can reject input like "1-2".
Do not Convert the input from the user immediately. Put it in a string and use Int32.TryParse(...) to find out whether or not a number was entered. Like this:
int i;
string input = Console.ReadLine();
if(Int32.TryParse(input, out i))
{
// it is a number and it is stored in i
}
else
{
// it is not a number
}
Note that
if (a < b) {
if (a < c) {
is equivalent to
if (a < b && a < c) {
and that this latter form introduces less nesting and is more readable, particularly if your code grows more complex. Also, you should probably never use Convert.ToInt32 - it has a particularly ill-conceived and surprising corner case; and it's also less type-safe than int.Parse which is the superior choice where possible - or int.TryParse when you're unsure whether the string is valid. Basically, avoid Convert.... wherever possible.
string Temp;
int tempInt,a;
bool result=false;
while ( result == false )
{
Console.Write ("\n Enter A Number : ");
Temp = Console.ReadLine ();
result = int.TryParse (Temp, out tempInt);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
a=tempInt;
break;
}
}
My preferred solution would be:
static void Main()
{
Console.WriteLine(
(
from line in Generate(()=>Console.ReadLine()).Take(3)
let val = ParseAsInt(line)
where val.HasValue
select val.Value
).Min()
);
}
static IEnumerable<T> Generate<T>(Func<T> generator) {
while(true) yield return generator();
}
static int? ParseAsInt(string str) {
int retval;
return int.TryParse(str,out retval) ? retval : default(int?);
}
Of course, depending on the specification (should invalid number be retried?), it may need to be tweaked.
Double/Float:
I'm just extending #Hans Passant answer (Taking care of DecimalSeparator and "-"):
static double ReadNumber()
{
var buf = new StringBuilder();
for (; ; )
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0)
{
Console.WriteLine();
return Convert.ToDouble(buf.ToString());
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0)
{
buf.Remove(buf.Length - 1, 1);
Console.Write("\b \b");
}
else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1)
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "")
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("0123456789".Contains(key.KeyChar))
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else
{
Console.Beep();
}
}
}
var getInput=Console.ReadLine();
int option;
//validating input
while(!int.TryParse(getInput, out option))
{
Console.WriteLine("Incorrect input type. Please try again");
getInput=Console.ReadLine();
}
Try This Simple
try
{
string x= "aaa";
Convert.ToInt16(x);
//if success is integer not go to catch
}
catch
{
//if not integer
return;
}