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 TextBox controls to read input from the keyboard.

    • Any data entered into a TextBox control is stored in the control's Text property as a string data type, regardless of whether the user typed numbers or letters.

    • Example: Entering the number 72 into a TextBox stores the string "72" inside the Text property.

  • Requirement for Data Type Conversion:

    • If numeric input from a TextBox needs to be assigned to a numeric variable for mathematical operations or storage, the Text property 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 the int data type.

    • double.Parse: Converts a string representation of a floating-point number into the double data type.

    • decimal.Parse: Converts a string representation of a monetary or high-precision value into the decimal data 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 40 into hoursWorkedTextBox, hoursWorkedTextBox.Text holds "40". int.Parse("40") processes the string, returns the integer 40, and the assignment operator (=) assigns 40 to hoursWorked.

    • 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.Text is passed as an argument to double.Parse. The converted double value is returned and assigned to temperature.

    • 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.Text is passed to decimal.Parse. The converted decimal value is returned and assigned to money.

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 Debugging button, pressing Shift + F5, or selecting Debug -> Stop Debugging from the menu.

    • Unhandled Exception Window: Stop the application by clicking the Quit button.

Displaying Numeric Values as Strings

  • Control Text Property Restriction:

    • The Text property of controls such as Label controls only accepts values of the string data type.

    • Directly assigning a numeric variable to a Text property results in a compilation error: csharp grossPayLabel.Text = grossPay; // ERROR! Cannot assign numeric data type directly to string Text property.         

  • The ToString Method:

    • All variables in C# possess a built-in ToString method 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: grossPay is initialized to 1550.0m. Calling grossPay.ToString() returns the string "1550.0". The assignment operator assigns "1550.0" to grossPayLabel.Text, displaying 1550.0 on 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 to MessageBox.Show(), displaying a popup message box with 123.

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". output receives "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:         MPG=Miles DrivenGallons of Gas Used\text{MPG} = \frac{\text{Miles Driven}}{\text{Gallons of Gas Used}}

  • 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 calculateButton and outputs to mpgLabel.

    • Closes the application when exitButton is clicked.

  • Development Steps:

    • Step 1: Create a new Windows Forms Application project named Fuel Economy.

    • Step 2: Design the form layout and set form Text property to Fuel Economy. Configure control properties according to Table 3.8.

    • Step 3: Implement calculateButton_Click event handler by double-clicking calculateButton in the Designer view. Write lines 22–38 of code.

    • Step 4: Implement exitButton_Click event handler by double-clicking exitButton. Write lines 43–44 of code.

    • Step 5: Save project. Press F5 or click Start Debugging button 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 = MiddleCenter

    • calculateButton (Button Control): Text = Calculate MPG

    • exitButton (Button Control): Text = Exit

  • Code Logic Breakdown for Event Handlers:

    • calculateButton_Click:

      • Line 22: double miles; (Declares double variable to store miles driven)

      • Line 23: double gallons; (Declares double variable to store gallons used)

      • Line 24: double mpg; (Declares double variable 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 the int data type?

    • Answer: The int.Parse method (e.g., int.Parse("40")).

  • Checkpoint 3.27:

    • Question: Write a statement that converts each of the specified string values to the decimal data type using the decimal.Parse method.

    • 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 decimal variable named total and a Label control named totalLabel. What will be the result when the assignment statement totalLabel.Text = total; is executed?

    • Answer: A compilation error occurs because a numeric value (decimal) cannot be directly assigned to a Label control's Text property, 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 int variable named result in the Text property of a Label control named resultLabel.

    • Answer: resultLabel.Text = result.ToString();