260 likes | 397 Views
Scope, Comments, Code Style, Keyboard Input. CS0007: Introduction to Computer Programming. Review. How would I write x = x + y; using combined assignment operators? x += y; How would I increment the variable x ? x++;
E N D
Scope, Comments, Code Style, Keyboard Input CS0007: Introduction to Computer Programming
Review • How would I write x = x + y; using combined assignment operators? • x += y; • How would I increment the variable x? • x++; • Because Java is a Strongly Typed Language before a value is assigned to a variable… • Java checks the types of the variable and the value being assigned to it to determine if they are compatible. • Rank as it applies to type means… • that if a type has a higher rank than another, it can hold more numbers, and thus, will not lose any precision.
Review • Ranks (Highest to Lowest): • double • float • long • int • short • Byte • A Widening Conversion is… • a conversion of a value to a higher-ranked type. • A Narrowing Conversion is… • a conversion of a value to a lower-ranked type. • Type Cast Operators allow you to… • manually convert from one type to another, even if it is a narrowing conversion.
Review • Two advantages of using a named constant: • If the value of the constant changes, you only need to change the line where the constant was initialized. • The name of the constant provided information about what it holds (sefl-documentation). • A String is not a primitive type in Java, it is a… • Class • A Class Type Variable (reference variable) does not hold the actual value, but... • the memory address of the data item it is associated with. • A Named Constant is… • a variable whose value is read only and cannot be changed during the program’s execution.
Review • A String object is not created for a String variable until… • The variable is assigned a value • String Methods: • length() • returns the number of characters in the string as an int • charAt(index) • index is an int value that specifies a character position in the string that is to be returned. The first character is at index 0. Return type is char. • toLowerCase() • returns a new string that is the lowercase equivalent of the string. • toUpperCase() • returns a new string that is the uppercase equivalent of the string.
Scope • Every variable has scope. • Scope refers to where in a program an entity can be accessed by name. • A variable is only visible to statements that are inside it’s scope. • Scoping rules are complex, we will only discuss a few right now. We’ll add to these later. • So far we’ve only seen variables declared inside of the main method. • Variables declared inside of a method are called local variables, and have local scope. • The scope of a local variable begins where they were declared and ends at the end of the method in which they were declared. • Also, you cannot have two local variables with the same name in the same scope
Scope Example • New Topics: • Local Scope
Comments • Internal Documentation takes the form of Comments in Java. • A Comment is… • line(s) in a program that is ignored by the compiler entirely. • Why do we have comments? • Include documentation inside of the code to allow other programmers (or ourselves) to understand what the code does, who wrote it, when, etc. • To temporarily make lines of code not executed instead of removing them outright • Three kinds of comments in Java • Single-Line – begin with // and the entire line is ignored • // Here is a comment • Multi-Line – begin with /* and end with */, and everything between is ignored • /* Here is a comment and it is still going on here */ • Documentation Comments – special comments that can be used to make attractively formatted HTML files that document the source code.
Comments • Your comments should do three things at this point • Give a block comment at the top of the file to give information about the file. In this class I want them to include: • Author’s name • The course number (CS0007) • The date created • A short description about what file is and does • Give information about what codes does, especially if you are worried the reader will not know what the code does, but even if you think it is obvious. • Either goes above the line, or next to it. • You can NEVER have too many comments. • Cite the source if a small snippet of code is taken from somewhere. • Later we will talk more about how to document different constructs as we get to them.
Block Comments • There are many styles to making block comments: //////////////////////////////////////// // One Style // Looks like this /////////////////////////////////////// /* * Another * Looks like this */ //-------------------------------------- // Yet another is // Looks like this //--------------------------------------
Commenting Example • New Topics: • Acceptable method of commenting
Documentation Comments • The Java SDK provides a tool for creating attractive, HTML-based, documentation files for your source code called javadoc. • The resulting documentation file can be viewed in any web browser. • Any comments that begin with /** and end in */ are considered javadoc comments, and can be used by javadoc. • Right, now, this has little use, because our programs are simple, but later they can be used to describe things like the methods and attributes of the classes we make. • To run javadoc program on a source code file, simply execute the command: javadoc sourceCodeFile.java
Documentation Comments Example • New Topics: • Documentation Comments • javadoc
Programming Style • Programming Style refers to the way a programmer uses spaces, indentation, blank lines, and punctuation characters to visually arrange a program’s source code. • This has NOTHING to do with syntax. • General Rule: Make your code easy to read. • We could write a program like this: public class Compact {public static void main(String [] args){int number = 5; System.out.println(number);}} • It even compiles and runs, but its really difficult to read.
Programming Style • Rule 1: All statements inside of a block should be indented one tab more than the statements directly outside of the block. public class Neat { public static void main(String [] args) { int number; … } } • Notice that all lines inside of the public class Neat headed block are tabbed once, and all lines inside of the public static void main… block are tabbed again. • Also note that the closing braces are in the same column as their headers.
Programming Style • Rule 2: Lines that are wrap onto the next line should be vertically aligned: System.out.println("Here I amgoing to " + "display a variable " + number); • Notice that instead of having the string wrap to the next line, the concatenation operator is used and the string begins where the last one did. • Also, if you are commenting variables, do something similar: intfahrenheit, //holds the Fahrenheit temperature celsius, //holds the Celsius temperature kelvin; //holds the Kelvin temperature
Programming Style • We’ve also went over some naming conventions: • Self-documenting code • Classes start with a capital letter • Variables start with a lowercase letter • Named Constants are all caps with underscores • We will add more good programming practices throughout the semester.
Reading Keyboard Input • Just like System.out object refers to the standard output device, the Java API provides an object, System.in, that refers to the standard input device. • The standard input device is normally the keyboard. • Unfortunately, using System.in is not as straight-forward as using System.out • System.in reads all input as bytes…which is often not very useful. • Fortunately, the Java API provides the Scanner class that allows us to retrieve input as primitive types or strings.
The Scanner Class • To create an object from the Scanner class that takes in keyboard input we use the line: Scanner keyboard =newScanner(System.in); • Scanner keyboard declares a variable named keyboard that is type Scanner. • Because Scanner is a class, keyboard is a reference variable. • =is the assignment operator, so we are initializing the keyboard variable. • new is a Java keyword that creates an object in memory, what follows it tells the compiler what object is to be created. • Scanner(System.in) tells the compiler that the object to be created is a Scanner object, and it should be associated with standard input. • This is called a constructor, and it creates the object in memory. • We will talk more about constructors much later in the course. • The result is that we have a reference variable, keyboard, that references a scanner object that is associated with standard input.
The Scanner Class • Some classes provided by the Java API are not automatically available for use with all programs, and the Java compiler needs to be told where to find them. • Scanner is one of these classes. • For this reason we must put the following line near the beginning of the file, outside of the class definition: import java.util.Scanner; • This tells the compiler where to find the definition for the Scanner class
The Scanner Class • The Scanner class provides methods for reading input as different types: • nextByte() – Returns input as a byte • nextDouble() – Returns input a double • nextFloat() – Returns input as a float • nextInt() – Returns input as an int • nextLine() – Returns input as a String • nextLong() – Returns input as a long • nextShort() – Returns input as a short • When associated with standard input, the user will be able to type characters on their keyboard and finish by pressing enter. • The result is then returned as the type specified by the method.
Scanner Example 1 • New Topics: • The Scanner class • Scanner constructor • nextInt() • nextDouble() • nextLine() • import statement
The Scanner Class • Notice there is no nextChar() method. • If you want to take in a single character, you must use the nextLine() method and use charAt(0) to retrieve the first character. • Example: ReadCharacter.java
The nextLine()method problem. • Let’s look at the program InputProblem.java. • It didn’t take in the user’s name at all! • The problem is that nextLine()works differently than the other Scanner class methods. • When the user types keystrokes at the keyboard, those keystrokes are stored in an area of memory sometimes called the keyboard buffer. • When the user pressed enter, the new line character is stored in the keyboard buffer. • When a user inputs a number for nextInt(), everything the user entered is stored in the keyboard buffer, including the newline character. Then, the value entered by the user is read from the buffer, leaving the newline character still in the buffer. • The nextDouble()method is designed so that it skips any leading newline characters it encounters, so when it tries to read the keyboard buffer, it sees the newline from nextInt(), it ignores it. • However, when nextLine() encounters the same situation, it is NOT designed to skip leading newline characters and assumes the user has pressed enter, stopping keyboard input.
The newLine()method problem. • Solution: • If you use another Scanner method before the nextLine()method, simply put another call to nextine()before the one that you want to take the user’s input. • Example: CorrectedInputProblem.java
Common Errors • Section 2.15 in the book provides a list of common errors to avoid, I suggest you read this.