98 Pages

ch02

Course: CSC 2310, Fall 2009
School: Bowling Green
Rating:
 
 
 
 
 

Word Count: 6856

Document Preview

2: Chapter Writing Java Programs Chapter 2 Writing Java Programs Java Programming FROM THE BEGI NNI NG 1 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.1 A Simple Java Program The following program displays the message Java rules! on the screen. JavaRules.java // Displays the message "Java rules!" public class JavaRules { public static void...

Register Now

Unformatted Document Excerpt

Coursehero >> Ohio >> Bowling Green >> CSC 2310

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
2: Chapter Writing Java Programs Chapter 2 Writing Java Programs Java Programming FROM THE BEGI NNI NG 1 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.1 A Simple Java Program The following program displays the message Java rules! on the screen. JavaRules.java // Displays the message "Java rules!" public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } Java Programming FROM THE BEGI NNI NG 2 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Java Programs in General Building blocks of a Java program: Classes. A class is a collection of related variables and/ or methods (usually both). A Java program consists of one or more classes. Methods. A method is a series of statements. Each class may contain any number of methods. Statements. A statement is a single command. Each method may contain any number of statements. Java Programming FROM THE BEGI NNI NG 3 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.2 Executing a Java Program Steps involved in executing a Java program: Enter the program Compile the program Run the program With an integrated development environment, all three steps can be performed within the environment itself. Java Programming FROM THE BEGI NNI NG 4 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Java Programming FROM THE BEGI NNI NG 5 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Integrated Development Environments An integrated development environment (IDE) is an integrated collection of software tools for developing and testing programs. A typical IDE includes at least an editor, a compiler, and a debugger. A programmer can write a program, compile it, and execute it, all without leaving the IDE. Java Programming FROM THE BEGI NNI NG 6 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Entering a Java Program Any editor or word processor can be used to enter a program, including Notepad or WordPad. If you use a word processor, be careful to save the file as a Text Document or as Text Only. You can also enter the program from a DOS window using the DOS edit program. Java Programming FROM THE BEGI NNI NG 7 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Compiling a Java Program Before compiling a program under Windows, open a DOS window and use the cd (change directory) command to select the directory that contains the program: cd c:\myfiles\java\programs To compile the program, use the javac command: javac JavaRules.java The file name must match the program name, and the .java extension must be included. Java Programming FROM THE BEGI NNI NG 8 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Running a Java Program If the compiler doesnt find any errors in the program, it creates a class file containing bytecode instructions. This file will have the same name as the program but with .class as the extension. To run a program, use the java command, which executes the Java interpreter. java requires that the name of a class file be specified (without the .class extension): java JavaRules Copyright 2000 W. W. Norton & Company. Java Programming FROM THE BEGI NNI NG 9 Chapter 2: Writing Java Programs Java Programming FROM THE BEGI NNI NG 10 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using Multiple Windows If you use edit to create and modify programs, it's a good idea to have two DOS windows open simultaneously. You can run edit in one window and use the other window to compile and test the program. Its also a good idea to enable the doskey utility when you go into a DOS window. doskey remembers previous commands that have been entered in that window. Java Programming FROM THE BEGI NNI NG 11 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.3 Program Layout The JavaRules program raises a couple of issues: Why do we put comments into programs, and what are the rules for doing so? How should we lay out a program? Does it matter where we put spaces and blank lines? Where should the curly braces go? Java Programming FROM THE BEGI NNI NG 12 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Comments Comments are an important part of every program. They provide information thats useful for anyone who will need to read the program in the future. Typical uses of comments: To document who wrote the program, when it was written, what changes have been made to it, and so on. To describe the behavior or purpose of a particular part of the program, such as a variable or method. To describe how a particular task was accomplished, which algorithms were used, or what tricks were employed to get the program to work. Java Programming FROM THE BEGI NNI NG 13 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Types of Comments Single-line comments: // Comment style 1 Multiline comments: /* Comment style 2 */ Doc comments: /** Comment style 3 */ Doc comments are designed to be extracted by a special program, javadoc. Java Programming FROM THE BEGI NNI NG 14 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Problems with Multiline Comments Forgetting to terminate a multiline comment may cause the compiler to ignore part of a program: System.out.print("My "); /* forgot to close this comment... System.out.print("cat "); System.out.print("has "); /* so it ends here */ System.out.println("fleas"); Java Programming FROM THE BEGI NNI NG 15 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Single-line Comments Many programmers prefer // comments to /* */ comments, for several reasons: Ease of use Safety Program readability Ability to comment out portions of a program Java Programming FROM THE BEGI NNI NG 16 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Tokens A Java compiler groups the characters in a program into tokens. The compiler then puts the tokens into larger groups (such as statements, methods, and classes). Tokens in the JavaRules program: public class JavaRules { public String [ ] args ) { System . "Java rules!" ) ; } } static out . void main println ( ( Java Programming FROM THE BEGI NNI NG 17 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Avoiding Problems with Tokens Always leave at least one space between tokens that would otherwise merge together: publicclassJavaRules { Dont put part of a token on one line and the other part on the next line: pub lic class JavaRules { Java Programming FROM THE BEGI NNI NG 18 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Indentation Programmers use indentation to indicate nesting. An increase in the amount of indentation indicates an additional level of nesting. The JavaRules program consists of a statement nested inside a method nested inside a class: Java Programming FROM THE BEGI NNI NG 19 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs How Much Indentation? Common amounts of indentation: 2 spaces: the bare minimum 3 spaces: the optimal amount 4 spaces: what many programmers use 8 spaces: probably too much The JavaRules program with an indentation of four spaces: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } Java Programming FROM THE BEGI NNI NG 20 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Brace Placement Brace placement is another important issue. One technique is to put each left curly brace at the end of a line. The matching right curly brace is lined up with the first character on that line: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } Java Programming FROM THE BEGI NNI NG 21 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Brace Placement Some programmers prefer to put left curly braces on separate lines: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } This makes it easier to verify that left and right braces match up properly. However, program files become longer because of the additional lines. Java Programming FROM THE BEGI NNI NG 22 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Brace Placement To avoid extra lines, the line containing the left curly brace can be combined with the following line: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } In a commercial environment, issues such as indentation and brace placement are often resolved by a coding standard, which provides a uniform set of style rules for all programmers to follow. Java Programming FROM THE BEGI NNI NG 23 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.4 Using Variables In Java, every variable must be declared before it can be used. Declaring a variable means informing the compiler of the variables name and its properties, including its type. int is one of Javas types. Variables of type int can store integers (whole numbers). Java Programming FROM THE BEGI NNI NG 24 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Declaring Variables Form of a variable declaration: The type of the variable The name of the variable A semicolon Example: int i; // Declares i to be an int variable Several variables can be declared at a time: int i, j, k; Its often better to declare variables individually. Java Programming FROM THE BEGI NNI NG 25 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Initializing Variables A variable is given a value by using =, the assignment operator: i = 0; Initializing a variable means to assign a value to the variable for the first time. Variables always need to be initialized before the first time their value is used. The Java compiler checks that variables declared in methods are initialized prior to their first use. Java Programming FROM THE BEGI NNI NG 26 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Initializers Variables can be initialized at the time theyre declared: int i = 0; 0 is said to be the initializer for i. If several variables are declared at the same time, each variable can have its own initializer: int i = 0, j, k = 1; Java Programming FROM THE BEGI NNI NG 27 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Changing the Value of a Variable The assignment operator can be used both to initialize a variable and to change the value of the variable later in the program: i = 1; i = 2; // Value of i is now 1 // Value of i is now 2 Java Programming FROM THE BEGI NNI NG 28 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Program: Printing a Lottery Number Lottery.java // Displays the winning lottery number public class Lottery { public static void main(String[] args) { int winningNumber = 973; System.out.print("The winning number "); System.out.print("in today's lottery is "); System.out.println(winningNumber); } } Java Programming FROM THE BEGI NNI NG 29 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.5 Types A partial list of Java types: int An integer double A floating-point number boolean Either true or false char A character Declarations of double, boolean, and char variables: double x, y; boolean b; char ch; Copyright 2000 W. W. Norton & Company. Java Programming FROM THE BEGI NNI NG 30 Chapter 2: Writing Java Programs Literals A literal is a token that represents a particular number or other value. Examples of int literals: 0 297 30303 48. 4.8e1 4.8e+1 .48e2 480e-1 Examples of double literals: 48.0 The only boolean literals are true and false. char literals are enclosed within single quotes: 'a' 'z' 'A' 'Z' '0' 31 '9' '%' '.' ' ' Java Programming FROM THE BEGI NNI NG Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using Literals as Initializers Literals are often used as initializers: double x = 0.0, y = 1.0; boolean b = true; char ch = 'f'; Java Programming FROM THE BEGI NNI NG 32 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.6 Identifiers Identifiers (names chosen by the programmer) are subject to the following rules: Identifiers may contain letters (both uppercase and lowercase), digits, and underscores (_). Identifiers begin with a letter or underscore. Theres no limit on the length of an identifier. Lowercase letters are not equivalent to uppercase letters. (A language in which the case of letters matters is said to be case-sensitive.) Java Programming FROM THE BEGI NNI NG 33 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Multiword Identifiers When an identifier consists of multiple words, its important to mark the boundaries between words. One way to break up long identifiers is to use underscores between words: last_index_of Another technique is to capitalize the first letter of each word after the first: lastIndexOf This technique is the one commonly used in Java. Java Programming FROM THE BEGI NNI NG 34 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Conventions A rule that we agree to follow, even though its not required by the language, is said to be a convention. A common Java convention is beginning a class name with an uppercase letter: Color FontMetrics String Names of variables and methods, by convention, never start with an uppercase letter. Java Programming FROM THE BEGI NNI NG 35 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Keywords The following keywords cant be used as identifiers because Java has already given them a meaning: abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try void volatile while null, true, and false are also reserved. Java Programming FROM THE BEGI NNI NG 36 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.7 Performing Calculations In general, the right side of an assignment can be an expression. A literal is an expression, and so is a variable. More complicated expressions are built out of operators and operands. In the expression 5 / 9, the operands are 5 and 9, and the operator is /. The operands in an expression can be variables, literals, or other expressions. Java Programming FROM THE BEGI NNI NG 37 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Operators Javas arithmetic operators: + * / % Addition Subtraction Multiplication Division Remainder 8 4 12 3 38 Copyright 2000 W. W. Norton & Company. Examples: 6+2 6-2 6*2 6/2 Java Programming FROM THE BEGI NNI NG Chapter 2: Writing Java Programs Integer Division If the result of dividing two integers has a fractional part, Java throws it away (we say that it truncates the result). Examples: 1/2 0 5/3 1 Java Programming FROM THE BEGI NNI NG 39 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs double Operands +, -, *, and / accept double operands: 6.1 6.1 6.1 6.1 6.1 6.1 6.1 6.1 + * / + * / 2.5 2.5 2.5 2.5 2 2 2 2 8.6 3.6 15.25 2.44 int and double operands can be mixed: 8.1 4.1 12.2 3.05 40 Copyright 2000 W. W. Norton & Company. Java Programming FROM THE BEGI NNI NG Chapter 2: Writing Java Programs Binary Operators The +, -, *, and / operators are said to be binary operators, because they require two operands. Theres one other binary arithmetic operator: % (remainder). The % operator produces the remainder when the left operand is divided by the right operand: 13 % 3 1 % is normally used with integer operands. Its a good idea to put a space before and after each binary operator. Java Programming FROM THE BEGI NNI NG 41 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Unary Operators Java also has two unary arithmetic operators: + Plus Minus Unary operators require just one operand. The unary + and - operators are often used in conjunction with literals (-3, for example). Java Programming FROM THE BEGI NNI NG 42 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Round-Off Errors Calculations involving floating-point numbers can sometimes produce surprising results. If d is declared as follows, its value will be 0.09999999999999987 rather than 0.1: double d = 1.2 - 1.1; Round-off errors such as this occur because some numbers (1.2 and 1.1, for example) cant be stored in double form with complete accuracy. Java Programming FROM THE BEGI NNI NG 43 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Operator Precedence Whats the value of 6 + 2 * 3? (6 + 2) * 3, which yields 24? 6 + (2 * 3), which yields 12? Operator precedence resolves issues such as this. *, /, and % take precedence over + and -. Examples: 5+2/2 8*3-5 6-1*7 9/4+6 6+2%3 5 + (2 / 2) (8 * 3) - 5 6 - (1 * 7) (9 / 4) + 6 6 + (2 % 3) 44 6 19 1 8 8 Copyright 2000 W. W. Norton & Company. Java Programming FROM THE BEGI NNI NG Chapter 2: Writing Java Programs Associativity Precedence rules are of no help when it comes to determining the value of 1 - 2 - 3. Associativity rules come into play when precedence rules alone arent enough. The binary +, -, *, /, and % operators are all left associative: 2 + 3 - 4 (2 + 3) - 4 1 2 * 3 / 4 (2 * 3) / 4 1 Java Programming FROM THE BEGI NNI NG 45 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Parentheses in Expressions Parentheses can be used to override normal precedence and associativity rules. Parentheses in the expression (6 + 2) * 3 force the addition to occur before the multiplication. Its often a good idea to use parentheses even when theyre not strictly necessary: (x * x) + (2 * x) - 1 However, dont use too many parentheses: ((x) * (x)) + ((2) * (x)) - (1) Java Programming FROM THE BEGI NNI NG 46 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Assignment Operators The assignment operator (=) is used to save the result of a calculation in a variable: area = height * width; The type of the expression on the right side of an assignment must be appropriate for the type of the variable on the left side of the assignment. Assigning a double value to an int variable is not legal. Assigning an int value to a double variable is OK, however. Java Programming FROM THE BEGI NNI NG 47 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using Assignment to Modify a Variable Assignments often use the old value of a variable as part of the expression that computes the new value. The following statement adds 1 to the variable i: i = i + 1; Java Programming FROM THE BEGI NNI NG 48 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Compound Assignment Operators The compound assignment operators make it easier to modify the value of a variable. A partial list of compound assignment operators: += -= *= /= %= Combines addition and assignment Combines subtraction and assignment Combines multiplication and assignment Combines division and assignment Combines remainder and assignment Java Programming FROM THE BEGI NNI NG 49 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Compound Assignment Operators Examples: i i i i i += -= *= /= %= 2; 2; 2; 2; 2; // // // // // Same Same Same Same Same as as as as as i i i i i = = = = = i i i i i + * / % 2; 2; 2; 2; 2; Java Programming FROM THE BEGI NNI NG 50 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Program: Converting from Fahrenheit to Celsius FtoC.java // Converts a Fahrenheit temperature to Celsius public class FtoC { public static void main(String[] args) { double fahrenheit = 98.6; double celsius = (fahrenheit - 32.0) * (5.0 / 9.0); System.out.print("Celsius equivalent: "); System.out.println(celsius); } } Java Programming FROM THE BEGI NNI NG 51 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.8 Constants A constant is a value that doesnt change during the execution of a program. Constants can be named by assigning them to variables: double freezingPoint = 32.0; double degreeRatio = 5.0 / 9.0; To prevent a constant from being changed, the word final can be added to its declaration: final double freezingPoint = 32.0; final double degreeRatio = 5.0 / 9.0; Java Programming FROM THE BEGI NNI NG 52 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Naming Constants The names of constants are often written entirely in uppercase letters, with underscores used to indicate boundaries between words: final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; Java Programming FROM THE BEGI NNI NG 53 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Adding Constants to the FtoC Program FtoC2.java // Converts a Fahrenheit temperature to Celsius public class FtoC2 { public static void main(String[] args) { final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; double fahrenheit = 98.6; double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO; System.out.print("Celsius equivalent: "); System.out.println(celsius); } } Java Programming FROM THE BEGI NNI NG 54 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Advantages of Naming Constants Advantages of naming constants: Programs easier are to read. The alternative is a program full of magic numbers. Programs are easier to modify. Inconsistencies and typographical errors are less likely. Always create meaningful names for constants. Theres no point in defining a constant whose name signifies its value: final int TWELVE = 12; Java Programming FROM THE BEGI NNI NG 55 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.9 Methods A method is a series of statements that can be executed as a unit. A method does nothing until it is activated, or called. To call a method, we write the name of the method, followed by a pair of parentheses. The methods arguments (if any) go inside the parentheses. A call of the println method: System.out.println("Java rules!"); Java Programming FROM THE BEGI NNI NG 56 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Methods in the Math Class The Math class contains a number of methods for performing mathematical calculations. These methods are called by writing Math.name, where name is the name of the method. The methods in the Math class return a value when they have completed execution. Java Programming FROM THE BEGI NNI NG 57 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs The pow and sqrt Methods The pow method raises a number to a power: Math.pow(2.0, 3.0) 8.0 Math.pow(-2.0, 3.0) 8.0 Math.pow(2.0, -1.0) 0.5 The sqrt method computes the square root of a number: Math.sqrt(2.0) 1.4142135623730951 Math.sqrt(4.0) 2.0 Both pow and sqrt return values of type double. Java Programming FROM THE BEGI NNI NG 58 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs The abs and max Methods The abs method computes the absolute value of a number: Math.abs(2.0) 2.0 Math.abs(-2.0) 2.0 Math.abs(2) 2 Math.abs(-2) 2 The max method finds the larger of two numbers: Math.max(3.0, 5.5) 5.5 Math.max(10.0, -2.0) 10.0 Math.max(12, -23) 12 Math.max(-5, -2) 2 Java Programming FROM THE BEGI NNI NG 59 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs The min Method The min method finds the smaller of two numbers: Math.min(3.0, 5.5) 3.0 Math.min(10.0, -2.0) 2.0 Math.min(12, -23) 23 Math.min(-5, -2) 5 The value returned by abs, max, and min depends on the type of the argument: If the argument is an int, the methods return an int. If the argument is a double, the methods return a double. Java Programming FROM THE BEGI NNI NG 60 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs The round Method The round method rounds a double value to the nearest integer: Math.round(4.1) 4 Math.round(4.5) 5 Math.round(4.9) 5 Math.round(5.5) 6 Math.round(-4.1) 4 Math.round(-4.5) 4 Math.round(-4.9) 5 Math.round(-5.5) 5 round returns a long value rather than an int value. Java Programming FROM THE BEGI NNI NG 61 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using the Result of a Method Call The value returned by a method can be saved in a variable for later use: double y = Math.abs(x); Another option is to use the result returned by a method directly, without first saving it in a variable. For example, the statements double y = Math.abs(x); double z = Math.sqrt(y); can be combined into a single statement: double z = Math.sqrt(Math.abs(x)); Java Programming FROM THE BEGI NNI NG 62 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using the Result of a Method Call Values returned by methods can also be used as operands in expressions. Example (finding the roots of a quadratic equation): double (-b double (-b root1 = + Math.sqrt(b * b - 4 * a * c)) / (2 * a); root2 = - Math.sqrt(b * b - 4 * a * c)) / (2 * a); Because the square root of b2 4ac is used twice, it would be more efficient to save it in a variable: double discriminant = Math.sqrt(b * b - 4 * a * c); double root1 = (-b + discriminant) / (2 * a); double root2 = (-b - discriminant) / (2 * a); Java Programming FROM THE BEGI NNI NG 63 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Using the Result of a Method Call The value returned by a method can be printed without first being saved in a variable: System.out.println(Math.sqrt(2.0)); Java Programming FROM THE BEGI NNI NG 64 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs 2.10 Input and Output Most programs require both input and output. Input is any information fed into the program from an outside source. Output is any data produced by the program and made available outside the program. Java Programming FROM THE BEGI NNI NG 65 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Displaying Output on the Screen Properties of System.out.print and System.out.println: Can display any single value, regardless of type. The argument can be any expression, including a variable, literal, or value returned by a method. println always advances to the next line after displaying its argument; print does not. Java Programming FROM THE BEGI NNI NG 66 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Displaying a Blank Line One way to display a blank line is to leave the parentheses empty when calling println: System.out.println("Hey Joe"); System.out.println(); // Write a blank line The other is to insert \n into a string thats being displayed by print or println: System.out.println("A hop,\na skip,\n\nand a jump"); Each occurrence of \n causes the output to begin on a new line. Java Programming FROM THE BEGI NNI NG 67 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Escape Sequences The backslash character combines with the character after it to form an escape sequence: a combination of characters that represents a single character. The backslash character followed by n forms \n, the new-line character. Java Programming FROM THE BEGI NNI NG 68 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Escape Sequences Another common escape sequence is \", which represents " (double quote): System.out.println("He yelled \"Stop!\" and we stopped."); In order to print a backslash character as part of a string, the string will need to contain two backslash characters: System.out.println("APL\\360"); Java Programming FROM THE BEGI NNI NG 69 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Printing Multiple Items The + operator can be used to combine multiple items into a single string for printing purposes: System.out.println("Celsius equivalent: " + celsius); At least one of the two operands for the + operator must be a string. Java Programming FROM THE BEGI NNI NG 70 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Obtaining Input from the User The SimpleIO class (not part of standard Java) simplifies the task of obtaining input. The SimpleIO.prompt method is first used to prompt the user: SimpleIO.prompt("Enter Fahrenheit temperature: "); Next, the SimpleIO.readLine method is used to read the users input: String userInput = SimpleIO.readLine(); Java Programming FROM THE BEGI NNI NG 71 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Obtaining Input from the User If the users input represents a number, it will need to be converted to numeric form. The Convert class (not part of standard Java) provides a toDouble method that converts a string to a double value: double fahrenheit = Convert.toDouble(userInput); To convert a string to an integer, the Integer.parseInt method is used instead: int n = Integer.parseInt(userInput); Java Programming FROM THE BEGI NNI NG 72 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Packages Java allows classes to be grouped into larger units known as packages. The package that contains SimpleIO and Convert is named jpb (Java Programming: From the Beginning). Java comes with a large number of standard packages. Java Programming FROM THE BEGI NNI NG 73 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Import Declarations Accessing the classes that belong to a package is done by using an import declaration: import package-name . * ; Import declarations go at the beginning of a program. A program that needs SimpleIO or Convert would begin with the line import jpb.*; Java Programming FROM THE BEGI NNI NG 74 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Application Programming Interfaces The packages that come with Java belong to the Java Application Programming Interface (API). In general, an API consists of code that someone else has written but that we can use in our programs. Typically, an API allows an application programmer to access a lower level of software. In particular, an API often provides access to the capabilities of a particular operating system or windowing system. Java Programming FROM THE BEGI NNI NG 75 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Program: Converting from Fahrenheit to Celsius (Revisited) FtoC3.java // Converts a Fahrenheit temperature entered by the user to // Celsius import jpb.*; public class FtoC3 { public static void main(String[] args) { final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; SimpleIO.prompt("Enter Fahrenheit temperature: "); String userInput = SimpleIO.readLine(); double fahrenheit = Convert.toDouble(userInput); double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO; System.out.println("Celsius equivalent: " + celsius); Copyright 2000 W. W. Norton & Company. } } Java Programming FROM THE BEGI NNI NG 76 Chapter 2: Writing Java Programs 2.11 Case Study: Computing a Course Average The CourseAverage program will calculate a class average, using the following percentages: Programs Quizzes Test 1 Test 2 Final exam 30% 10% 15% 15% 30% The user will enter the grade for each program (0 20), the score on each quiz (010), and the grades on the two tests and the final (0100). There will be eight programs and five quizzes. Java Programming FROM THE BEGI NNI NG 77 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Output of the CourseAverage Program Welcome to the CSc 2310 average calculation program. Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Program Program Program Program Program Program Program Program Quiz Quiz Quiz Quiz Quiz 1 2 3 4 5 1 2 3 4 5 6 7 8 score: score: score: score: score: score: score: score: 20 19 15 18.5 20 20 18 20 score: score: score: score: score: 9 10 5.5 8 9.5 Enter Test 1 score: 78 Enter Test 2 score: 92 Enter Final Exam score: 85 Course average: 88 Java Programming FROM THE BEGI NNI NG 78 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Design of the CourseAverage Program 1. Print the introductory message ("Welcome to the CSc 2310 average calculation program"). 2. Prompt the user to enter eight program scores. 3. Compute the program average from the eight scores. 4. Prompt the user to enter five quiz scores. 5. Compute the quiz average from the five scores. 6. Prompt the user to enter scores on the tests and final exam. 7. Compute the course average from the program average, quiz average, test scores, and final exam score. 8. Round the course average to the nearest integer and display it. Java Programming FROM THE BEGI NNI NG 79 Copyright 2000 W. W. Norton & Company. Chapter 2: Writing Java Programs Design of the CourseAverage Program double variables can be used to store scores and averages. Computing the course average involves scaling the program average and quiz average so that they lie between 0 and 100: courseAverage = .30 programAverage 5 + .10 quizAverage 10 + .15 test1 + .15 test2 + .30 finalExam Java Programming FROM THE BEGI NNI NG Math.round can be used to round the course average to the nearest integer. Copyright 2000 W. W. Norton & 80 Company. Chapter 2: Writing Java Programs CourseAverage.java // // // // // // // // // // // // // // // // // // Program name: CourseAverage Author: K. N. King Written: 1998-04-05 Modified: 1999-01-27 Prompts the user to enter eight program scores (0-20), five quiz scores (0-10), two test scores (0-100), and a final exam score (0-100). Scores may contain digits after the decimal point. Input is not checked for validity. Displays the course average, computed using the following formula: Programs Quizzes Test 1 Test 2 Final exam 30% 10% 15% 15% 30% Copyright 2000 W. W. Norton & Company. The course average is rounded to the nearest integer. Java Programming FROM THE BEGI NNI NG 81 Chapter 2: Writing Java Programs import jpb.*; public class CourseAverage { public static void main(String[] args) { // Print the introductory message System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n"); // Prompt the user to enter eight program scores SimpleIO.prompt("Enter Program 1 score: "); String userInput = SimpleIO.readLine(); double program1 = Convert.toDouble(userInput); ...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Bowling Green - CSC - 2010
Chapter9:TheTowerof BabelInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn aboutProcedural languages Special-purpose languages Alternative programming paradigmsInvitationtoComputerScienc
Bowling Green - CSC - 2010
Chapter 5: Computer Systems OrganizationInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn aboutThe components of a computer system Putting all the pieces together-the Von Neumann architecture
Bowling Green - CSC - 2310
Chapter 6: GraphicsChapter 6GraphicsJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 6: Graphics6.1 Creating a Drawing Javas Abstract Window Toolkit (AWT) provides classes and other tools that are us
Bowling Green - CSC - 2310
Chapter 7: Class Variables and MethodsChapter 7Class Variables and MethodsJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 7: Class Variables and Methods7.1 Class Methods Versus Instance Methods Revi
Bowling Green - CSC - 2310
Chapter 1: Getting StartedChapter 1Getting StartedJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 1: Getting Started1.1 What Do Computers Do? A computer system is an integrated collection of hardwar
Bowling Green - CSC - 2010
Chapter 8: Introduction to HighLevel Language ProgrammingInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn about Where do we stand? High-level languages Introduction to Java Virtual data
Bowling Green - CSC - 2010
Chapter6:AnIntroduction toSystemSoftwareand VirtualMachinesInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn about System software Assemblers and assembly languageOperating systems2Inv
Bowling Green - CSC - 2010
Chapter2:Algorithm DiscoveryandDesignInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn aboutRepresenting algorithmsExamples of algorithmic problem solvingInvitationtoComputerScience,Jav
Bowling Green - CSC - 2310
Chapter 4: Basic Control StructuresChapter 4Basic Control StructuresJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 4: Basic Control Structures4.1 Performing Comparisons Most programs need the abili
Bowling Green - CSC - 2010
Chapter7:Computer Networks,theInternet,and theWorldWideWebInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn aboutBasic networking concepts Communication protocols Network services and benefits
Bowling Green - CSC - 2310
Chapter 11: SubclassesChapter 11SubclassesJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 11: Subclasses11.1 Inheritance In the real world, objects aren't usually one-of-akind. Both cars and trucks
Bowling Green - CSC - 2010
Chapter13:Electronic CommerceandInformation SecurityInvitation to Computer Science, Java Version, Third EditionObjectivesIn this chapter, you will learn aboutE-commerce Databases Information securityInvitationtoComputerScience,JavaVersio
Bowling Green - CSC - 2310
Chapter 10: Writing ClassesChapter 10Writing ClassesJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 10: Writing Classes10.1 Designing Classes As programs get larger, good design becomes increasingly
Bowling Green - CSC - 2310
Chapter 13: Data StructuresChapter 13Data StructuresJava ProgrammingFROM THE BEGI NNI NG1Copyright 2000 W. W. Norton & Company.Chapter 13: Data Structures13.1 Multidimensional Arrays Multidimensional arrays have more than one dimensi
Bowling Green - CSC - 8350
e0cd159fd07258ba53ee417ab8faa2e0479c4c57.doc Page 1 of 2 CSC 8350, Advanced Software Engineering (2009 Spring) Abstract for Research Topic Mary Hudachek-Buswell, Wooyoung Kim, Anjum Rayaz-Ahmed Security Challenges, Modeling, Enhancement and Solutions
Bowling Green - CSC - 8350
UML Tutorial: Finite State MachinesRobert C. Martin Engineering Notebook Column C+ Report, June 98In my last column I presented UML sequence diagrams. Sequence diagrams are one of the many tools in UML that support dynamic modeling. In this column
Bowling Green - CSC - 8840
Introduction to Systems Modeling & SimulationDr. Xiaolin HuDr. Xiaolin HUOutline Syllabus A general view of M&S Systems concept S t t The framework of M&SDr. Xiaolin HUCSC8840: Discrete Event Modeling & Simulation Instructor: Xiaoli
Bowling Green - CSC - 8350
ResearchProjectLiteratureReviewCSC8350AdvancedSoftwareEngineering Spring,2009ModelDrivenApproachto DataWarehousesChetanV.Kokate GeetikaSharma VijayNeelakandanABSTRACTData warehouses store historical and aggregated information, extracted from
Bowling Green - CSC - 8350
An Approach to Wrap Legacy Applications into Web ServicesAbstract The change in business needs in terms of new solutions required organizations to move towards re-architecting their IT infrastructure. There are several means of re-architecting; one
Bowling Green - CANDI - 71
CCCS Client ServicesThe following screen will appear:Training ManualVerify the clients e-mail address and update if necessary. Check the Attach Document box. Click the Submit Information button. Client Clients get two e-mails during the ePresen
Bowling Green - KWHITE - 31
PRODUCT GUIDEwas founded in order to manufacture quality park model homes. We build both a rustic log cabin SUPerior Park and a more modern vinyl or stucco series home, offering amenities and upgrades generally not available in park model homes toda
Bowling Green - KWHITE - 31
pot-free shine with 0 e . AI d WI on~ l,ird00524-9797,e .6119.White 1Kelie White Dr. Lopez Engli h 3080 10 February 2007 Visual Argument: Everclean Faucet Finish Shocking, stunning and subtlety accepted the child of about five years of age slur
Bowling Green - CWALKER - 37
Southeastrans presents:Workstation ConfigurationSpecific StandardizationsCourse Contents Overview: Appropriate software and hardware for Southeastrans Lesson 1: Operating System Lesson 2: Antivirus Lesson 3: Windows Lesson 4: Remote Assist
Bowling Green - SMARTI - 2
Bowling Green - SMARTI - 2
Bowling Green - CPHELPS - 1
Chloe Phelps Director of Researchcphelps@Plopt.org www.plotp.org806. 555. 5555 806. 555. 5566 P.O. Box 1234 Atlanta, GA 30345Chloe Phelps Director of ResearchP.O. Box 1234 Atlanta, GA 30345phone: (806) 555-5555 fax: (806) 555-5566 cphelps@Pl
Bowling Green - CPHELPS - 1
Sara L. MayPresent Address 2319 99th Drive Lubbock, TX 79412 (806) 755-5555 Permanent Address: P.O. Box 600000 Field, TX 7900000 (806) 777-7777Email: sara@myfavorite.comProfileCreative, motivated, reliable individual seeks position with Clear Ch
Bowling Green - DCALMEIDA - 1
VenezolanosofGeorgiaEnglish/Spanish SearchgoNewsTravel To Venezuela forlessIndexHomeAbout News Events Food Education Newsletter ChatroomFornearly48hoursVenezuelan televisionandradiostationslackedcoverage oflastweeksfailedcoupagainstPreside
Bowling Green - DCALMEIDA - 1
Hear AllProtecting Your Hearing for an Audible Tomorrow Causes of Hearing Loss Exposure to very loud noises over a long period of time (everyday sounds) Aging Viral or bacterial infections Exhaustion Understanding Volume Norma
Bowling Green - DGROGAN - 2
About the Bears Bears that I have Links Where I Got My Info Contact Me Our Mission StatementClick on the name of a bear to view more info on it#1 Bear [1997 Holiday Teddy Bear 1998 Holiday Teddy Bear 1999 Holiday Teddy Bear 1999 Signature Bear 200
Bowling Green - DGROGAN - 2
Based out of Oklahoma City, Oklahoma Opened in 1972; Now over 200 stores and 11,000 employees Company based on old time traditions and values Closed on Sunday Close at 8pm throughout the week Instill a lot of trust in employees, especially cash
Bowling Green - DGROGAN - 2
Based out of Oklahoma City, Oklahoma Opened in 1972; Now over 200 stores and 11,000 employees Company based on old time traditions and values Closed on Sunday Close at 8pm throughout the week Instill a lot of trust in employees, especially cash
Bowling Green - BOLIVETTI - 1
Olivetti 1 Beatriz Olivetti Eng 3100 April 06, 2006 Voices The use of the personal pronoun I has been the source of much conversation among scholars during the past two decades. During the early 1970s, Expressionist Rhetoric theory emerged from theor
Bowling Green - TEMPEST - 4
I wrote this paper hoping that it would be published in an annual provided by the organization to its members and others who may want to gain knowledge about the organization. I felt that a question and answer format would be best suitable for this t
Bowling Green - SABRAM - 1
Stephanie Abram English 2150 Intro. to Rhetoric & Advanced Comp. Encyclopedia EssayCiceroMarcus Tullius Cicero was born January 3, 106 BC in Arpinum, which is a town about 70 miles southeast of Rome (May & Wisse 6), and he died December 7, 43 BC
Bowling Green - JALTENOR - 1
The essay 20th Century Poetry is a comparison between two poems. For this assignment we were required to choose two poems which spoke about a particular theme in different ways. Written for ENGL 3720 20th Century English poetry, we were also to inclu
Bowling Green - JALTENOR - 1
Jennifer Altenor HistThry&Prac. Expository writing On the Street Where I lived There was so much life on the street where I lived. People were as colorful as a bag of skittles. When my friends and I were too lazy to walk to Lenox Park or too boring t
Bowling Green - SABRAM - 1
Stephanie Abram English 3100 History/Theory Paper The Classical/Ancient Period Greece/Rome The Classical/Ancient period is the most important period of rhetoric because that is when it started. The Greeks conceived the formal study of rhetoric someti
Bowling Green - DMA - 05
DavidM.Abercrombie March27,2003 English3090 HighBrow/LowBrowPaperWhatYouWanttoKnowandHowYouWanttoKnowItIntroductionThediscussionofGeorgiaPoliticsisaverypopulartopic,butveryfewdoitonahigh level.MostlyGeorgiapublicationsareillequippedtocovertheongo
Bowling Green - BMANNING - 1
Bernice Manning April 30, 2002 My Philosophy of CompositionIn the article, A Brief History of Rhetoric and Composition, the 1970's period deals with the way cognitive processes influenced writing. Theorists, such as Richard Young, Alton Becker, and
Bowling Green - JALTENOR - 1
Jennifer Alter Dr. Schatteman 20th Century Poetry Literary AnalysisArt: From the Observer & The Observed Poetry is at its most descriptive when it is inspired by another art form. In the poems "Leaving the Tate" by Fleur Adcock and "Standing Female
Bowling Green - GPULLMAN - 1
I have never witnessed a comic routine that I would say after seeing it, "I will always remeber where I was when I saw the most amazing comic routine in history." Hyperbole, perhaps, but I, at this moment feel like I will never forget it. Stephen Col
Bowling Green - PROJECT - 1
Here's the reminder you asked for regarding my first two visuals that wouldn't upload due to size.
Bowling Green - DREID - 2
Ditanjah Reid English 3080 Mr. George Pullman July 30, 2002Verbal and nonverbal communication are important fundamentals of human interactions. Verbal communication is complex and misunderstood. When wecommunicate verbally we either use rhetoric
Bowling Green - DREID - 2
Ditanjah Reid English 3080 Mr. George Pullman August 1, 2002There are many things in life that we take for granted. For example, oxygen, vision, and the rain are things that people rarely consider. Most of us probably never give thought to the rela
Bowling Green - MTALLENT - 1
Tallent 1 Matthew Tallent English 3290 Galchinsky/Hall-Godsey Feburary 23 2006 Aristocracy vs. Meritocracy in Persuasion Jane Austen lived in 17th and 18th century England, a time when heritage and wealth almost solely determined who someone was and
Bowling Green - SROBERTS - 79
Harriet Jacobs: Voice of Determination & ResistanceSherman RobertsHarriet Jacobs's Incidents in the Life of a Slave Girl expresses the author's attempt to present to white audiences, mainly middle-class women, the many evils of slavery. Jacobs do
Bowling Green - CSC - 1010
Test 1 ReviewChapter 1 A world of computers 1. Widespread use of computer technology 2. Computer literacy What is a computer? 1. Definition of computer 2. Differentiate between data and information. Emphasize that data is processed into information.
Bowling Green - CSC - 1010
Students User ManualVersion 4.0Copyright 2007 by Thomson Course Technology. All rights reserved. This publication is protected by federal copyright law. No part of this publication may be reproduced without prior permission in writing from Thomso
Bowling Green - CSC - 1010
Discovering Computers 2008Chapter 9 Communication s and NetworksChapter 9 ObjectivesDiscuss the components required for successful communications Identify various sending and receiving devices Describe uses of computer communications Describe co
Bowling Green - CSC - 1010
ConceptsandTechniques FourthEditionHTMLProject 1Introduction to HTMLProject Objectives Describe the Internet and its associated key terms Describe the World Wide Web and its associated key terms Identify the types and purposes of Web sites
Bowling Green - CSC - 1010
Discovering Computers 2008Chapter 11 Computer Security, Ethics and PrivacyChapter 11 ObjectivesDescribe the types of computer security risks Identify ways to safeguard against computer viruses, worms, Trojan horses, botnets, denial of service at
Bowling Green - CSC - 1010
Discovering Computers 2008Chapter13 Programming Languagesand Program DevelopmentChapter13ObjectivesDescribe various ways to develop Web pages including HTML, scripting languages, DHTML, XML, WML, and Web page authoring softwareDifferentiate be
Bowling Green - CSC - 1010
Discovering Computers 2008Chapter 3 Application SoftwareChapter 3 ObjectivesIdentify the categories of application software Explain ways software is distributed Explain how to work with application software Identify the key features of widely us
Bowling Green - CSC - 1010
Business SoftwareWhat is database software? Allows you to create, access, and manage dataAdd, change, delete, sort, and retrieve datap. 145NextBusiness SoftwareWhat are the parts of a database? A table contains records A record is a ro
Bowling Green - CSC - 1010
Multiple choice (2*40=80 points) Use the Answer Sheet. There is only one correct answer to each question. 1. _ is/are the steps that tell the computer how to perform a particular task. a. Data b. Information symbol on the screen called the pointer. a
Bowling Green - CSC - 1010
Assignment 4Chapter 71. To start up, a computer locates _. a. application software in storage and loads it into memory b. application software in memory and loads it onto storage c. an operating system in storage and loads it into memory d. an oper
Bowling Green - CSC - 1010
Assignment 2 Print assignment 2 out and write the correct answer on the left side of each question. Submit your papers with answers. Due Date: Thursday, 09/06/2007 before the class. Chapter 1Multiple Choice1. As computers become more a part of eve
Bowling Green - CSC - 1010
SyllabusCSC 1010 Computer & ApplicationDepartment of Computer Science Georgia State University Fall 2007 Instructor: Feng Gu Class Hours: Tuesday & Thursday, 11:00 am-12:15 pm, ALC 233 Office Hours: Monday, 2:00 pm-3: 30 pm and by appointment, 34 P
Bowling Green - CSC - 1010
Extra credit 3: Quiz for Chapter 4Name 1. On _, the electronic components and most storage devices are part of the system unit and other devices, such as the keyboard, mouse, and monitor, normally occupy space outside the system unit. a. desktop per
Bowling Green - CSC - 1010
Final Exam Review Chapter 11 1. What is computer security risk? 2. What are viruses, worms, and Trojan horses? 3. Macro virus. 4. How does an antivirus program inoculate a program file? 5. What is zombie? 6. How can you make your password more secure