Chapter 3 Readings: 3.5 Inputting and Outputting Numeric Values
Inputting and Outputting Numeric Data
Graphical User Interface (GUI) Input Basics:
GUI applications typically use
TextBoxcontrols to read input from the keyboard.Any data entered into a
TextBoxcontrol is stored in the control'sTextproperty as a string data type, regardless of whether the user typed numbers or letters.Example: Entering the number
72into aTextBoxstores the string"72"inside theTextproperty.
Requirement for Data Type Conversion:
If numeric input from a
TextBoxneeds to be assigned to a numeric variable for mathematical operations or storage, theTextproperty value must first be converted to the target numeric data type.Cast operators cannot be used to convert a string data type to a numeric data type.
Converting Strings to Numeric Data Types via Parse Methods
Definition of Parsing:
In computer science, to parse means to analyze a string of characters for a specific purpose.
In the .NET Framework, Parse methods are specialized methods used to analyze character strings and convert them into specific numeric data types.
Required Directive:
The
using System;directive must be present at the top of a C# form source code file to utilize the standard Parse methods.
Primary Parse Methods:
int.Parse: Converts a string representation of an integer into theintdata type.double.Parse: Converts a string representation of a floating-point number into thedoubledata type.decimal.Parse: Converts a string representation of a monetary or high-precision value into thedecimaldata type.
Method Execution Mechanics:
Argument: The string to be converted is passed into the Parse method as an argument.
Return Value: The method converts the string argument and returns the converted numeric value.
Code Examples and Step-by-Step Traces:
Converting to Integer (
int.Parse): ```csharp // Declare an int variable to hold the hours worked. int hoursWorked;// Get the hours worked from the TextBox. hoursWorked = int.Parse(hoursWorkedTextBox.Text); ```
Execution Trace: If a user enters
40intohoursWorkedTextBox,hoursWorkedTextBox.Textholds"40".int.Parse("40")processes the string, returns the integer40, and the assignment operator (=) assigns40tohoursWorked.
Converting to Double (
double.Parse): ```csharp // Declare a double variable to hold the temperature. double temperature;// Get the temperature from the TextBox. temperature = double.Parse(temperatureTextBox.Text); ```
Execution Trace:
temperatureTextBox.Textis passed as an argument todouble.Parse. The converteddoublevalue is returned and assigned totemperature.
Converting to Decimal (
decimal.Parse): ```csharp // Declare a decimal variable to hold an amount of money. decimal money;// Get an amount from the TextBox. money = decimal.Parse(moneyTextBox.Text); ```
Execution Trace:
moneyTextBox.Textis passed todecimal.Parse. The converteddecimalvalue is returned and assigned tomoney.
Handling Invalid Conversions and Exceptions
Conditions for Parsing Failures:
Parse methods require the input string to contain valid numeric characters compatible with the specified target data type.
If the input string contains invalid non-numeric characters (e.g.,
"xyz") or numbers outside the range of the target type, an error occurs.
Definition of Exception:
An exception is an unexpected runtime error that occurs while a program is running.
If an exception is not properly handled or dealt with by code, it causes the program to halt execution immediately.
In developer terminology, when an exception happens, an exception is said to be "thrown".
Example Scenario:
Executing
hoursWorked = int.Parse(hoursWorkedTextBox.Text);when the user entered"xyz"throws an unhandled exception because"xyz"cannot be parsed into an integer.
Halting Application Execution During Debugging:
Standard Exception Dialog Window: Stop the application by clicking the
Stop Debuggingbutton, pressingShift + F5, or selectingDebug->Stop Debuggingfrom the menu.Unhandled Exception Window: Stop the application by clicking the
Quitbutton.
Displaying Numeric Values as Strings
Control Text Property Restriction:
The
Textproperty of controls such asLabelcontrols only accepts values of the string data type.Directly assigning a numeric variable to a
Textproperty results in a compilation error:csharp grossPayLabel.Text = grossPay; // ERROR! Cannot assign numeric data type directly to string Text property.
The
ToStringMethod:All variables in C# possess a built-in
ToStringmethod that converts the variable's numeric value into a string.General Format:
variableName.ToString()
Displaying Values in Label Controls:
csharp decimal grossPay = 1550.0m; grossPayLabel.Text = grossPay.ToString(); Execution Trace:
grossPayis initialized to1550.0m. CallinggrossPay.ToString()returns the string"1550.0". The assignment operator assigns"1550.0"togrossPayLabel.Text, displaying1550.0on the UI.
Displaying Values in Message Boxes:
Arguments passed to
MessageBox.Show()must be string expressions or converted to strings prior to invocation.csharp int myNumber = 123; MessageBox.Show(myNumber.ToString()); Execution Trace:
myNumber.ToString()returns string"123"."123"is passed toMessageBox.Show(), displaying a popup message box with123.
Implicit String Conversion with the Addition Operator
Dual Functionality of the
+Operator:String Concatenation: Executed when both operands are strings.
Numeric Addition: Executed when both operands are compatible numeric types.
Implicit Conversion Behavior:
When an expression uses
+with one string operand and one numeric operand, C# implicitly converts the numeric operand to a string and concatenates the two operands.
Code Examples:
Implicit Conversion in Variable Assignment:
csharp int idNumber = 1044; string output = "Your ID number is " + idNumber; Result:
idNumber(1044) is implicitly converted to"1044".outputreceives"Your ID number is 1044".
Implicit Conversion in Message Box Display:
csharp double testScore = 88.5; MessageBox.Show("Your test score is " + testScore); Result:
testScore(88.5) is implicitly converted to"88.5". Message box displays"Your test score is 88.5".
Tutorial 3.2: Calculating Fuel Economy Application Step-by-Step Guide
Mathematical Formula for Fuel Economy:
Fuel economy in the United States is measured in miles per gallon (MPG).
Formula:
Application Overview:
Calculates and displays fuel economy based on user inputs for miles driven (
milesTextBox) and gallons of gas used (gallonsTextBox).Calculates MPG upon clicking
calculateButtonand outputs tompgLabel.Closes the application when
exitButtonis clicked.
Development Steps:
Step 1: Create a new Windows Forms Application project named
Fuel Economy.Step 2: Design the form layout and set form
Textproperty toFuel Economy. Configure control properties according to Table 3.8.Step 3: Implement
calculateButton_Clickevent handler by double-clickingcalculateButtonin the Designer view. Write lines 22–38 of code.Step 4: Implement
exitButton_Clickevent handler by double-clickingexitButton. Write lines 43–44 of code.Step 5: Save project. Press
F5or clickStart Debuggingbutton to run and test input values.
Control Specifications (Table 3.8):
milesPromptLabel(Label Control):Text=Enter the number of miles driven:gasPromptLabel(Label Control):Text=Enter the gallons of gas used:outputDescriptionLabel(Label Control):Text=Your car’s MPG:milesTextBox(TextBox Control): Standard defaults (No properties changed)gallonsTextBox(TextBox Control): Standard defaults (No properties changed)mpgLabel(Label Control):AutoSize=False,BorderStyle=FixedSingle,Text=(cleared/erased),TextAlign=MiddleCentercalculateButton(Button Control):Text=Calculate MPGexitButton(Button Control):Text=Exit
Code Logic Breakdown for Event Handlers:
calculateButton_Click:Line 22:
double miles;(Declaresdoublevariable to store miles driven)Line 23:
double gallons;(Declaresdoublevariable to store gallons used)Line 24:
double mpg;(Declaresdoublevariable to store calculated MPG)Line 28:
miles = double.Parse(milesTextBox.Text);(Parses input text to double)Line 32:
gallons = double.Parse(gallonsTextBox.Text);(Parses input text to double)Line 35:
mpg = miles / gallons;(Calculates division ratio)Line 38:
mpgLabel.Text = mpg.ToString();(Converts double result to string for display)
exitButton_Click:Line 44:
this.Close();(Closes the form)
Complete Form Source Code: Program 3-2
Full Program Listing:
csharp 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace Fuel_Economy 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void calculateButton_Click(object sender, EventArgs e) 21 { 22 double miles; // To hold miles driven 23 double gallons; // To hold gallons used 24 double mpg; // To hold MPG 25 26 // Get the miles driven and assign it to 27 // the miles variable. 28 miles = double.Parse(milesTextBox.Text); 29 30 // Get the gallons used and assign it to 31 // the gallons variable. 32 gallons = double.Parse(gallonsTextBox.Text); 33 34 // Calculate MPG. 35 mpg = miles / gallons; 36 37 // Display the MPG in the mpgLabel control. 38 mpgLabel.Text = mpg.ToString(); 39 } 40 41 private void exitButton_Click(object sender, EventArgs e) 42 { 43 // Close the form. 44 this.Close(); 45 } 46 } 47 }
Checkpoint Questions and Answers
Checkpoint 3.26:
Question: What method converts the string literal
"40"to a value of theintdata type?Answer: The
int.Parsemethod (e.g.,int.Parse("40")).
Checkpoint 3.27:
Question: Write a statement that converts each of the specified string values to the
decimaldata type using thedecimal.Parsemethod.Answers:
a.
"9.05":decimal.Parse("9.05")b.
grandTotal:decimal.Parse(grandTotal)c.
"50":decimal.Parse("50")d.
priceTextBox.Text:decimal.Parse(priceTextBox.Text)
Checkpoint 3.28:
Question: Suppose an application has a
decimalvariable namedtotaland aLabelcontrol namedtotalLabel. What will be the result when the assignment statementtotalLabel.Text = total;is executed?Answer: A compilation error occurs because a numeric value (
decimal) cannot be directly assigned to aLabelcontrol'sTextproperty, which only accepts strings.
Checkpoint 3.29:
Question: Write a statement that displays each of the specified numeric variables in a message box.
Answers:
a.
grandTotal:MessageBox.Show(grandTotal.ToString());b.
highScore:MessageBox.Show(highScore.ToString());c.
sum:MessageBox.Show(sum.ToString());d.
width:MessageBox.Show(width.ToString());
Checkpoint 3.30:
Question: Write a statement that will store the value of an
intvariable namedresultin theTextproperty of aLabelcontrol namedresultLabel.Answer:
resultLabel.Text = result.ToString();