Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Computer Science Notes Chapter 2 Page 1 of 24 Chapter 2: Elementary Programming These notes are meant to accompany Introduction to Java Programming: Brief Version, seventh edition by Y. Daniel Lang. Programming Skills in a Nutshell: At the end of this chapter you should have the following programming skills: 1. Declare numeric variables to store numbers and perform calculations with those numeric variables. 2. Declare string and character variables to store text. 3. To get information from the user of a program. 4. To program with proper style. 5. To understand the fundamental flow of any program: a. Tell the user what the program does. b. Get any needed information, either from the user or from another input source. c. Perform any needed calculations. d. Report results as output to the monitor or other output source. 6. To understand how to translate a programming problem into code: a. Decide what the program is supposed to do (unless someone tells you first). b. Decide what information you’ll need, where you’ll get it, and where you’ll store it. c. Write out how you would do the task yourself. d. Translate that task into code using the programming techniques you have at your disposal. 7. Here is a template using the key programming skills you should have at this point: Computer Science Notes Chapter 2 Page 2 of 24 import java.util.Scanner; // The import statement tells the compiler where to find additional classes that will be used. // In this case, the Scanner class will be used, which reads in and stores keystrokes from the keyboard. /**The Chap02Basics class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output in a console. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */ public class Chap02Basics { /** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */ public static void main(String[] args) { //Tell the user what the program does System.out.println("This program will calculate the hypotenuse, perimeter, and area " + "of a right triangle given the lengths of its legs."); // ******************************************************************** // Here is the portion of the code that reads data into memory. // ******************************************************************** //Declare variables for the data to be read in: i.e., the lengths of the two legs double legA, legB; //Declare a String object to store the uer's name, //and initalize that String to store the name Clyde String userName = "Clyde"; //Create a Scanner object for reading in the user's input Scanner keyboard = new Scanner(System.in); //Prompt the user for his/her name, and store in userName System.out.println("Please enter your name: "); userName = keyboard.next(); //Prompt the user for the lengths of the legs, //and store those two pieces of information in legA and legB. System.out.println("Please enter the length of the " + "first leg of the right triangle:"); legA = keyboard.nextDouble(); System.out.println("Please enter the length of the " + "second leg of the right triangle:"); legB = keyboard.nextDouble(); Computer Science Notes Chapter 2 Page 3 of 24 // ******************************************************************** // Here is the portion of the code that // performs calculations on the data in memory. // ******************************************************************** //Declare variables for the quantities to be calculated. double hypotenuse, perimeter , area; //Calculate the hypotenuse using the Pythagorean Theorem: // a^2 + b^2 = c^2 // c = sqrt(a^2 + b^2) hypotenuse = Math.sqrt(legA*legA + legB*legB); //Calculate the perimeter by adding up the lengths of the three sides. perimeter = legA + legB + hypotenuse; //Calculate the area using the formula area = (1/2)(base)(height). area = 0.5 * legA * legB; // // // // ******************************************************************** Here is the portion of the code that displays memory values for output. ******************************************************************** //Report the results for hypotenuse. System.out.println(); System.out.println("Okay, " + userName + ", the hypotenuse of your " + "right triangle is: " + hypotenuse); //Report the results for perimeter. System.out.println("The perimeter of your " + "right triangle is: " + perimeter); //Report the results for area System.out.println("The area of your " + "right triangle is: " + area); //Tell the user that the program is done. System.out.println("\nI hope you enjoyed your results."); }//end of method main(String[]) }//end of class Chap02Basics This program will calculate the hypotenuse, perimeter, and area of a right triangle given the lengths of its legs. Please enter your name: Kevin Please enter the length of the first leg of the right triangle: 3 Please enter the length of the second leg of the right triangle: 4 Okay, Kevin, the hypotenuse of your right triangle is: 5.0 The perimeter of your right triangle is: 12.0 The area of your right triangle is: 6.0 I hope you enjoyed your results. Computer Science Notes Chapter 2 Page 4 of 24 Book’s Statement of Skills: 1. To write Java programs to perform simple calculations (2.2) 2. To use identifiers to name variables, constants, methods, and classes (2.3) 3. To use variables to store data (2.4 – 2.5) 4. To program with assignment statements and assignment operators (2.5) 5. To use constants to store permanent data (2.6) 6. To declare Java primitive types: byte, short, int, long, float, double, and char. (2.7 – 2.8) 7. To use Java operators to write numeric expressions. (2.7 – 2.8) 8. To represent characters using the char type. (2.9) 9. To represent a string using the String type. (2.10) 10. To obtain input from the console using the Scanner class. (2.11-2.12) 11. To become familiar with Java documentation, programming style, and naming conventions. (2.13) 12. To distinguish syntax errors, runtime errors, and logic errors. (2.14) 13. To debug logic errors. (2.15) 14. (GUI) To obtain input using JOptionPane input dialog boxes. (2.11) Computer Science Notes Chapter 2 Page 5 of 24 Section 2.1: Introduction This chapter will teach you how to use primitive data types, perform input and output, and execute simple calculations. Section 2.2: Writing Simple Programs When you write a program: 1. Decide what information you’ll need and how you’ll store it (i.e., the data structures), and where you’ll get the data (from disk or the user) a. Data structures introduced in this chapter: VARIABLES i. Primitive data types 1. Integers 2. Floating-point numbers 3. Characters 4. Boolean data types (for true/false) ii. Strings – for arrays of characters (i.e., words and sentences) 2. Write out how you would perform the computation yourself; i.e., outline your algorithm. An algorithm is a statement of how to solve a problem in terms of the steps to execute, and the order of those steps. 3. Decide what kind of information you want your program to show when it is done computing and the format of that information. 4. Translate that task into code using the programming techniques you have at your disposal. Computer Science Notes Chapter 2 Page 6 of 24 Practice: Go through the steps above to decide how to write a program to compute the area of a rectangle, then implement (i.e., write) the program. Plan for writing a program to compute the area of a rectangle: 1. Information needed and how to store it 2. Algorithm: 3. Information to show and its format: 4. Translate that task into code using the programming techniques you have at your disposal. Program to compute the area of a rectangle: Computer Science Notes Chapter 2 Page 7 of 24 VARIABLE: a piece of memory with a name used for storing data and computational results. Choose descriptive names for variables. o Example: good variable names to represent the legs of a right triangle would be legA and legB as opposed to a and b. Variables must be declared in Java before they are used so that the JVM can set aside the appropriate amount of memory. Example: //Declare variables for the data to be stored: i.e., the lengths of the two legs double legA, legB; //Declare variables for the quantities to be calculated. double hypotenuse, perimeter , area; The equals sign ( = ) is used to assign a value to a variable. Example: //Calculate the area using the formula area = (1/2)(base)(height). area = 0.5 * legA * legB; The plus sign ( + ) is used to perform addition and to concatenate strings with other strings or numerical values. If a string is too long, then you should break it up over two lines using concatenation. Examples: //Calculate the perimeter by adding up the lengths of the three sides. perimeter = legA + legB + hypotenuse; System.out.println("Okay, " + userName + ", the hypotenuse of your " + "right triangle is: " + hypotenuse); Computer Science Notes Chapter 2 Page 8 of 24 Section 2.3: Identifiers An identifier is the name of any programming entity you create, like a variable, constant, method, class, or package. Rules for naming identifiers: An identifier is a sequence of letters, digits, the underscore ( _ ), or the dollar sign ( $ ). An identifier must start with a letter, underscore ( _ ), or the dollar sign ( $ ). It can not start with a digit. An identifier can not be a reserved word (like class, double, or int). An identifier can not be the words true, false, or null. An identifier can be any length. Tips for naming identifiers: Identifiers are case sensitive; legA is different from lega. Use descriptive names, like cylinderRadius instead of r for the radius of a cylinder. Use “camel type” or underscores to break up long names into easy-to-recognize pieces, like cylinderRadius or triangle_perimeter. By convention, the $ is only used to start an identifier name in mechanically generated source code. By convention, primitive data type identifiers start with a lower-case letter. By convention, constants are capitalized. By convention, method identifiers start with a lower-case letter. By convention, class identifiers start with an upper -case letter. Section 2.4: Variables Variables are used to store data in a program. They can be reassigned new values as many times as you want. Section 2.4.1: Declaring Variables Variables must be declared in Java before they are used so that the JVM can set aside the appropriate amount of memory for the variable. This is because different types of data are stored in different ways and use different amounts of memory, and thus require different algorithms for calculating with them. See the table below for the different primitive data types. A statement that declares a variable is called a variable declaration. The syntax for a single variable declaration is: datatype variableName; Example: double hypotenuse; The syntax for multiple variable declarations of the same type is: datatype variableName1, variableName2, variableName3, …; Example: double legA, legB; To declare and initialize a variable in one statement: datatype variableName1 = value; Example: double area = 0.0; Computer Science Notes Chapter 2 Page 9 of 24 Java Primitive Data Types Type int double char boolean short long byte float Description An integer in the range -2,147,483,648 int 2,147,483,647 These range limits are stored in java.lang.Integer.MIN_VALUE and java.lang.Integer.MAX_VALUE Double-precision floating point: 10308 and about 15 significant figures These range limits are stored in java.lang.Double.MIN_VALUE and java.lang.Double.MAX_VALUE Character type, using Unicode The type with 2 truth values: true and false A short integer in the range -32768 short 32767 These range limits are stored in java.lang.Short.MIN_VALUE and java.lang.Short.MAX_VALUE A long integer in the range -9,223,372,036,854,775,808 long 9,223,372,036,854,775,807 These range limits are stored in java.lang.Long.MIN_VALUE and java.lang.Long.MAX_VALUE -128 integer byte 127 These range limits are stored in java.lang.Byte.MIN_VALUE and java.lang.Byte.MAX_VALUE Single-precision floating point: 1038 and about 7 significant figures These range limits are stored in java.lang.Float.MIN_VALUE and java.lang.Float.MAX_VALUE See: http://en.wikipedia.org/wiki/IEEE_floating-point_standard Size 4 bytes (32-bit signed) 8 bytes (64-bit IEEE 754) (1 bit for the sign; 11 bits for the exponent; 52 bits for the fraction) 2 bytes 1 bit 2 bytes (16-bit signed) 8 bytes (64-bit signed) 1 byte (8-bit signed) 4 bytes (32-bit IEEE 754) (1 bit for the sign; 8 bits for the exponent; 23 bits for the fraction) Computer Science Notes Chapter 2 Page 10 of 24 Section 2.5: Assignment Statements and the Assignment Operator An assignment statement assigns a value to a variable. Java uses the equals sign ( = ) for the assignment operator, or symbol that tells the JVM to store a value in a variable’s memory location. An expression is a collection of values, variables, and operators that represent a computation. Example: //Calculate the area. area = 0.5 * legA * legB; //Calculate the perimeter. perimeter = legA + legB + hypotenuse; A variable can be used in the expression of its own assignment statement. This is quite common… Example: //increment the variable counter. counter = counter + 1; An assignment expression is an assignment statement that is part of another statement. The value used by the statement is computed after the assignment is made. Examples: The assignment expression statement System.out.println( x = 1); i = j = k = 2; Is equaivalent to: x = 1; System.out.println(x); k = 2; j = k; i = j; Section 2.5: Declaring and Initializing Variables in One Step The statement int j = 5; int j = 5, k = 7; Example of an initialization error: int luckyNumber; System.out.println(luckyNumber); // ERROR - uninitialized variable Is equaivalent to: int j; j = 5; int j, k; j = 5; k = 7; Computer Science Notes Chapter 2 Page 11 of 24 Section 2.6: Constants A constant represents a value that never changes. To declare a constant, precede its data type with the keyword final. By convention, use capital letters for a constant’s identifier. Constants are a good programming technique because: o You don’t have to repeatedly type the same number when writing the program. o The value can be changed in a single location, if necessary. o A descriptive name for the constant makes the program easy to read. Example: Compute the area of a circle. final double PI = 3.1415927; double radius = 2.5; double area; area = radius * radius * PI; Note: you can access the value of pi to 15 digits using the constant for pi stored in the math class: Math.PI: double radius = 2.5; double area; area = radius * radius * Math.PI; Section 2.7: Numeric Data Types and Operations -- See table on page 7… We’ll mostly use int and double this semester for numeric variables. Overflow is when you try to assign a value to a variable that is too large for the variable to hold. Underflow is when you try to assign a value to a variable that is too small for the variable to hold. Section 2.7.1: Numeric Operators Operator + Meaning Addition * / Subtraction Multiplication Division % Note: integer division only keeps the quotient and discards the remainder Remainder (integers only) Example 34 + 1 29.5 + 2.7E2 -88.2 + 5 34 – 0.1 300 * 30 1.0 / 2.0 24 / 2 1/2 Result 35 299.5 -83.2 33.9 9000 0.5 12 0 20 % 3 2 Note: + and – are both unary and binary operators… Note: many simple floating – point numbers do not have an exact binary representation, and thus get rounded off… Computer Science Notes Chapter 2 Page 12 of 24 System.out.println(1.0 – 0.9); Displays 0.0999999999999998 instead of 0.1 Example from the book, page34: (Note: you can download all the source code in the book from http://www.cs.armstrong.edu/liang/intro7e/studentsolution.html) public class DisplayTime { public static void main(String[] args) { int seconds = 500; int minutes = seconds / 60; int remainingSeconds = seconds % 60; System.out.println(seconds + " seconds is " + minutes + " minutes and " + remainingSeconds + " seconds"); } } //Where are all the comments??? 500 seconds is 8 minutes and 20 seconds Section 2.7.2: Numeric Literals A literal is a constant value that appears in a program. An integer literal is assumed to be an int. For longer integer literals, append an L to the literal: 2147483648L To denote an octal literal, use a zero prefix: 07577 To denote a hexadecimal literal, use a 0x prefix: 0xFFFF A floating-point literal is assumed to be a double. For float literals, append an f or F to the literal: 23.5F Scientific notation: 1.23456103 = 1.23456e3 = 1.23456e+3; Section 2.7.3: Evaluating Java Expressions Java follows standard mathematical order of operations Practice: Translate the following calculation into Java: 4 9 x 3 4 x 20 y 5 a b c z 9 5 3x y x 2.510-4 = 2.5e-4 Computer Science Notes Chapter 2 Page 13 of 24 Section 2.7.4: Shorthand Operators … can be used when the variable in the expression is stores the resulting answer… Operator += -= *= /= %= ++var Meaning Addition Assignment Subtraction Assignment Multiplication Assignment Division Assignment Remainder Assignment Preincrement var++ Postincrement --var Predecrement var-- Postdecrement Example i += 8 i -= 8 i *= 8 Equivalent i = i + 8 i = i - 8 i = i * 8 i /= 8 i = i / 8 i %= 8 i = i % 8 Increments var by 1 and uses the new value in var in the expression Uses the old value in var in the expression, then increments var Decrements var by 1 and uses the new value in var in the expression Uses the old value in var in the expression, then decrements var Section 2.8: Numeric Type Conversions …are done automatically by the compiler: 1. If one of the operands is a double, then the other is converted to double. 2. Otherwise, if one of the operands is a float, then the other is converted to float. 3. Otherwise, if one of the operands is a long, then the other is converted to long. 4. Otherwise, both operands are converted to int. Type casting explicitly converts data type by placing desired data type in parentheses in front of variable: int i = 1, j = 3; System.out.println(i / j); //output is 0 System.out.println((float)i / (float)j); //output is 0.333333333 Type casting can be used to round off numbers to a desired number of decimal places. The following example rounds off a monetary amount to two decimals: public class SalesTax { public static void main(String[] args) { double purchaseAmount = 197.55; double tax = purchaseAmount * 0.06; System.out.println("Unformatted sales tax is " + tax); System.out.println("Formatted sales tax is " + (int)(tax * 100) / 100.0); } } Unformatted sales tax is 11.853 Formatted sales tax is 11.85 Computer Science Notes Chapter 2 Page 14 of 24 Section 2.9: Character Data Type and Operations The data type char is used to represent individual characters. A character literal is enclosed in single quotes. Example: public class CharExample { public static void main(String[] args) { char letter1 = 'K'; char letter2 = 'A'; char letter3 = 'M'; char numChar = '4'; System.out.println("My initials are: " + letter1 + letter2 + letter3); System.out.println("The value of numChar is: " + numChar); System.out.println("One more than numChar is: " + (numChar+1)); } } My initials are: KAM The value of numChar is: 4 One more than numChar is: 53 Section 2.9.1: Unicode and ASCII code Character encoding is the process of converting a character to its binary representation. How characters are encoded is called an encoding scheme. ASCII is a 7-bit encoding scheme that was meant to display English uppercase and lowercase letters, digits, and punctuation marks. There are 128 ASCII characters. Unicode is the encoding scheme used by Java, and Unicode was meant to display all written characters in all the languages of the world using16 bits (2 bytes), which corresponds to 65,536 characters. This, however, was not enough choices for all the characters in the world. Supplementary Unicode represents all the characters that go beyond the 16-bit limit, and will not be discussed in this class. Computer Science Notes Chapter 2 Page 15 of 24 Section 2.9.2: Escape Sequences for Special Characters Escape sequences are designed to display special characters in string literals. Escape sequences are preceded by a backslash public class EscapeSequenceExample { public static void main(String[] args) { System.out.println("He said \"Java is Fun\".\n\"Java is Fun.\""); } } He said "Java is Fun". "Java is Fun." \b \t \n \f \r \\ \’ \” backspace tab linefeed formfeed carriage return backslash single quote double quote Computer Science Notes Chapter 2 Page 16 of 24 Section 2.9.3: Casting Between char and Numeric Data Types When an integer is cast to a char, only the lower 16 bits of data are used. When a float or double is cast to a char, the floating-point value is cast to an int, which is then cast to a char. When a char is cast to a numeric type, the character’s Unicode value is cast to the specified numeric type. Section 2.10: The String Type The data type of String is used to store a string (or sequence) of characters. The String type is not a primitive data type; it is a reference type (more in Chap07). Strings can be concatenated with the + operator. public class StringExamples { public static void main(String[] args) { String message1 = "Welcome to Java."; String message2 = "Welcome " + "to " + "Java."; System.out.println("message1 = " + message1); System.out.println("message2 = " + message2); System.out.println(); String message3 = "Chapter " + 2; String message4 = "Supplement " + 'B'; System.out.println("message3 = " + message3); System.out.println("message4 = " + message4); System.out.println(); message2 += " Java is fun!"; System.out.println("message2 = " + message2); System.out.println(); int i = 2, j = 3; System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("concatenation: i + j = " + i + j); System.out.println("addition: i + j = " + (i + j)); } } message1 = Welcome to Java. message2 = Welcome to Java. message3 = Chapter 2 message4 = Supplement B message2 = Welcome to Java. Java is fun! i = 2 j = 3 concatenation: i + j = 23 addition: i + j = 5 Also see http://faculty.matcmadison.edu/kmirus/20082009A/804208/804208LP/Chap02StringBasics.java Computer Science Notes Chapter 2 Page 17 of 24 Section 2.11: Console Input Using the Scanner Class Recall that Java uses System.out (i.e., a data field named out in the System class) to refer to the "standard" output stream or device, which is a console displayed on the monitor. To perform console output, we saw that we can use the println method with System.out (officially, println is a method of the PrintStream class, since out is an object of type PrintStream). Just as Java has a standard output device, it also has a standard input device. Java uses System.in (i.e., a data field named in of the System class) to refer to the "standard" input stream or device, which is the keyboard. To get access to the data flowing into the computer from the keyboard, we can use the Scanner class, which has several methods for reading different types of input from the keyboard. To use the Scanner class to read input you need to do three things: 1. Have the following statement as the very beginning of your source code: import java.util.Scanner; 2. Create a “variable” to store the information from the scanner. Use the following line of source code: Scanner keyboard = new Scanner(System.in); (You can change the variable name keyboard to whatever you want, but that is the only thing you can change.) 3. Store information from the scanner into primitive variables or strings using an appropriate method of the scanner class. Here are seven examples of seven key input methods: a. String userName = keyboard.next(); //the String is delimited by spaces b. int a = keyboard.nextInt(); c. double x = keyboard.nextDouble(); d. float y = keyboard.nextFloat(); e. byte b = keyboard.nextByte(); f. short c = keyboard.nextShort(); g. long d = keyboard.nextLong(); The program at the start of these notes uses the next and nextDouble methods. Method nextByte() nextShort() nextInt() nextLong() nextFloat() nextDouble() next() nextLine() Methods for Scanner objects Description Reads an integer of the byte type Reads an integer of the short type Reads an integer of the int type Reads an integer of the long type Reads a number of the float type Reads a number of the double type Reads a string that ends before a whitespace Reads a line of characters (i.e., string ending with a line separator) A Scanner object reads items separated by whitespaces. A whitespace is one of the following characters: , \t, \f, \r, \n Computer Science Notes Chapter 2 Page 18 of 24 import java.util.Scanner; // Scanner is in java.util public class TestScanner { public static void main(String args[]) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter an integer System.out.print("Enter an integer: "); int intValue = input.nextInt(); System.out.println("You entered the integer " + intValue); // Prompt the user to enter a double value System.out.print("Enter a double value: "); double doubleValue = input.nextDouble(); System.out.println("You entered the double value " + doubleValue); // Prompt the user to enter a string System.out.print("Enter a string without space: "); String string = input.next(); System.out.println("You entered the string " + string); } } Enter an integer: 596 You entered the integer 596 Enter a double value: 56.3 You entered the double value 56.3 Enter a string without space: hello You entered the string hello Enter an integer: 53 96 .3hello kevin You entered the integer 53 Enter a double value: You entered the double value 96.0 Enter a string without space: You entered the string .3hello Section 2.12: Case Studies See www.cs.armstrong.edu/liang/intro7e/book/ComputeLoan.java See www.cs.armstrong.edu/liang/intro7e/book/ComputeChange.java See www.cs.armstrong.edu/liang/intro7e/book/ShowCurrentTime.java Section 2.13: Programming Style and Documentation Programming style deals with how the source code to a program looks: Documentation is the body of explanatory remarks and comments pertaining to a program. Section 2.13.1: Appropriate Comments and Comment Styles At the start of a program, include a summary of what the program does, its key features, its supporting data structures, and any unique techniques it uses. A long program should also have comments that introduce each major step and explain anything that is difficult to read. Computer Science Notes Chapter 2 Page 19 of 24 javadoc comments ( /** … */ ) are used to give information about classes, methods, and public variables. Comments of this type can be read by the javadoc utility program which generates HTML support documents from them. Section 2.13.2: Naming Conventions Use descriptive names with straightforward meanings for your variables, constants, classes, and methods. Names are case-sensitive. Start the names of variables and methods with a lowercase letter. Start the names of classes with an uppercase letter. Capitalize every letter in the name of a constant. Section 2.13.3: Proper Indentation and Spacing Indent lines of code by the same amount that are at the same “nesting level” in a program. Put a single blank space on either side of a binary operator. Section 2.13.4: Block Styles A block is a group of statements surrounded by (curly) braces, { }. In end-of-line style, the opening brace for the block is at the end of the line. In next-line style, the opening brace for the block is at the start of the next line. /**Here is a simple program written using the end-of-line block style. */ public class BlockStyleTest { public static void main(String[] args) { System.out.println("Block Styles."); } } /**Here is a simple program written using the next-line block style. */ public class BlockStyleTest { public static void main(String[] args) { System.out.println("Block Styles."); } } Section 2.14: Programming Errors Section 2.14.1: Syntax Errors A syntax error is an error that occurs during program compilation. Syntax errors result from errors in code construction, like mistyping a keyword, omitting necessary punctuation, not declaring a variable before it is used, or having unmatched pairs of braces or parentheses. Section 2.14.2: Runtime Errors A runtime error is an error that occurs during program execution. Runtime errors result when the program is supposed to perform an operation that is impossible to carry out, like divide by zero, open a disk file that does not exist, or store a letter in a floating-point data type. Computer Science Notes Chapter 2 Page 20 of 24 Section 2.14.3: Logic Errors A logic error is an error that occurs because the code you wrote is not logically consistent with what you wanted the program to do. Logic errors can result when you type the wrong variable name, or do any one of ten million other bone-headed things. Section 2.15: Debugging Debugging is the process of finding errors in your code and correcting them. Syntax errors are usually easier to debug, because the compiler tells you which lines of code have syntax errors. Runtime errors are also fairly easy to debug, because the program will crash with an error message telling you which line of code caused the error. Logic errors are tough to debug, because they do not cause any visible problems. o Logic errors can be debugged by hand by hand-tracing through the lines of code in a program, keeping track of variable values, and seeing where things go wrong. o Logic errors can also be traced using a debugger utility, like the jdb command-line debugger in the JDK. o Eclipse also has a built-in debugger, which allows you to Execute code a single line at a time Trace into or step over methods Set breakpoints where the program stops and lets you look at execution a line at a time Display variables Display call stacks Modify variables Section 2.16: (GUI) Getting Input from Dialog Boxes The JOptionPane class has a method called showInputDialog that creates a GUI (Graphical User Interface) dialog box for reading in data. It basically provides a window with a title in a title bar, an icon in the title bar, a close button in the title bar, and an icon, text prompt, text box, an OK button, and a Cancel button. The showInputDialog method returns a string copy of what was typed into the text box. Here is the program from the start of these notes re-written using dialog boxes: import javax.swing.JOptionPane; // The import statement tells the compiler where to find the JOptionPane class, // which contains the code for dialog boxes. /**The Chap02BasicsGUI class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output using a GUI interface of dialog boxes. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */ public class Chap02BasicsGUI { Computer Science Notes Chapter 2 Page 21 of 24 /** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */ public static void main(String[] args) { //Tell the user what the program does JOptionPane.showMessageDialog(null, "This program will calculate " + "the hypotenuse, perimeter, and area of a right triangle " + "given the lengths of its legs.", "Chap02BasicsGUI Intro", JOptionPane.INFORMATION_MESSAGE); // ******************************************************************** // Here is the portion of the code that reads data into memory. // ******************************************************************** //Declare variables for the data to be read in: i.e., the lengths of the two legs double legA, legB; //Input dialog boxes return strings as output, so we also need a String object //for each numeric variable, which will then get converted to doubles. String legA_String, legB_String; //Declare a String object to store the user's name. String userName; //Prompt the user for his/her name, and store in userName userName = JOptionPane.showInputDialog(null, "Please enter your name.", "Your name", JOptionPane.QUESTION_MESSAGE); //Prompt the user for the length of the first leg. legA_String = JOptionPane.showInputDialog(null, "Please enter the " + "length of the first leg of the right triangle:", "First Leg", JOptionPane.QUESTION_MESSAGE); //Convert the string from the input dialog box to a double-precision //number, and store the answer in legA legA = Double.parseDouble(legA_String); //Prompt the user for the length of the second leg, //then convert the string to a number and store in legB legB_String = JOptionPane.showInputDialog(null, "Please enter the " + "length of the second leg of the right triangle:", "Second Leg", JOptionPane.QUESTION_MESSAGE); legB = Double.parseDouble(legB_String); // ******************************************************************** // Here is the portion of the code that // performs calculations on the data in memory. // ******************************************************************** //Declare variables for the quantities to be read calculated. double hypotenuse, perimeter , area; //Calculate the hypotenuse using the Pythagorean Theorem: // a^2 + b^2 = c^2 // c = sqrt(a^2 + b^2) hypotenuse = Math.sqrt(legA*legA + legB*legB); Computer Science Notes Chapter 2 Page 22 of 24 //Calculate the perimeter by adding up the lengths of the three sides. perimeter = legA + legB + hypotenuse; //Calculate the area using the formula area = (1/2)(base)(height). area = 0.5 * legA * legB; // ******************************************************************** // Here is the portion of the code that displays // memory values for output. // ******************************************************************** //Report the results for hypotenuse String hypotenuseString = "Okay, " + userName + ", the hypotenuse of your " + "right triangle is: " + hypotenuse; JOptionPane.showMessageDialog(null, hypotenuseString, "Hypotenuse Results", JOptionPane.INFORMATION_MESSAGE); //Report the results for perimeter String perimeterString = "The perimeter of your right triangle is: " + perimeter; JOptionPane.showMessageDialog(null, perimeterString, "Perimeter Results", JOptionPane.INFORMATION_MESSAGE); //Report the results for area String areaString = "The area of your right triangle is: " + area; JOptionPane.showMessageDialog(null, areaString, "Area Results", JOptionPane.INFORMATION_MESSAGE); //Tell the user that the program is done. JOptionPane.showMessageDialog(null, "I hope you enjoyed your results.", "All Done", JOptionPane.INFORMATION_MESSAGE); }//end of main(String[]) }//end of class Chap02BasicsGUI Computer Science Notes Chapter 2 Page 23 of 24 Computer Science Notes Chapter 2 Page 24 of 24 Section 2.16.1: Converting Strings to Numbers If a string contains a sequence of characters meant to represent a number, then you can convert that string to a number using either the parseInt method of the Integer class, or the parseDouble method of the Double class. String stringX = "123"; int x = Integer.parseInt(stringX); System.out.println("x + 5 = " + (x + 5)); String stringY = "456.789"; double y = Double.parseDouble(stringY); System.out.println("y + 5 = " + (y + 5)); Section 2.16.2: Using Input Dialog Boxes Also see www.cs.armstrong.edu/liang/intro7e/book/ComputeLoanUsingInputDialog.java