scope, comments, code style, keyboard input

Click here to load reader

Upload: wei

Post on 24-Feb-2016

46 views

Category:

Documents


0 download

DESCRIPTION

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++; - PowerPoint PPT Presentation

TRANSCRIPT

PowerPoint Presentation

CS0007: Introduction to Computer ProgrammingScope, Comments, Code Style, Keyboard Input1ReviewHow 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 variableJava 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 meansthat if a type has a higher rank than another, it can hold more numbers, and thus, will not lose any precision.

2ReviewRanks (Highest to Lowest):doublefloatlongintshortByteA 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 tomanually convert from one type to another, even if it is a narrowing conversion.

3ReviewTwo 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 aClassA 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 isa variable whose value is read only and cannot be changed during the programs execution.

4ReviewA String object is not created for a String variable untilThe variable is assigned a valueString Methods:length()returns the number of characters in the string as an intcharAt(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.

5ScopeEvery 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 its scope.Scoping rules are complex, we will only discuss a few right now. Well add to these later.So far weve 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 scope6Scope ExampleNew Topics:Local Scope7CommentsInternal 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 outrightThree kinds of comments in JavaSingle-Line begin with // and the entire line is ignored// Here is a commentMulti-Line begin with /* and end with */, and everything between is ignored/* Here is a commentand 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.

8CommentsYour comments should do three things at this pointGive a block comment at the top of the file to give information about the file. In this class I want them to include:Authors nameThe course number (CS0007)The date createdA short description about what file is and doesGive 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.

9Block CommentsThere are many styles to making block comments:

////////////////////////////////////////// One Style// Looks like this///////////////////////////////////////

/** Another* Looks like this*/

//--------------------------------------// Yet another is// Looks like this//--------------------------------------10Commenting ExampleNew Topics:Acceptable method of commenting11Documentation CommentsThe 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.java12Documentation Comments ExampleNew Topics:Documentation Commentsjavadoc13Programming StyleProgramming Style refers to the way a programmer uses spaces, indentation, blank lines, and punctuation characters to visually arrange a programs 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 staticvoid main(String [] args){int number = 5; System.out.println(number);}}It even compiles and runs, but its really difficult to read.

14Programming StyleRule 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.15Programming StyleRule 2: Lines that are wrap onto the next line should be vertically aligned:System.out.println("Here I am going 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:int fahrenheit, //holds the Fahrenheit temperature celsius, //holds the Celsius temperature kelvin; //holds the Kelvin temperature

16Programming StyleWeve also went over some naming conventions:Self-documenting codeClasses start with a capital letterVariables start with a lowercase letterNamed Constants are all caps with underscoresWe will add more good programming practices throughout the semester.17Reading Keyboard InputJust 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.outSystem.in reads all input as byteswhich is often not very useful.Fortunately, the Java API provides the Scanner class that allows us to retrieve input as primitive types or strings.18The Scanner Class To create an object from the Scanner class that takes in keyboard input we use the line:Scanner keyboard = new Scanner(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.19The Scanner ClassSome 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 class20The Scanner ClassThe Scanner class provides methods for reading input as different types:nextByte() Returns input as a bytenextDouble() Returns input a doublenextFloat() Returns input as a floatnextInt() Returns input as an intnextLine() Returns input as a StringnextLong() Returns input as a longnextShort() Returns input as a shortWhen 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.

21Scanner Example 1New Topics:The Scanner classScanner constructornextInt()nextDouble()nextLine()import statement22The Scanner ClassNotice 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

23The nextLine() method problem.Lets look at the program InputProblem.java.It didnt take in the users 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. 24The 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 users input.Example: CorrectedInputProblem.java25Common ErrorsSection 2.15 in the book provides a list of common errors to avoid, I suggest you read this.26