Download Lesson 6 Notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Review
1) Two advantages of using a named constant:
2) A String is not a primitive type in Java, it is a…
3) A Class Type Variable (reference variable) does not hold the actual value, but...
4) A Named Constant is…
5) A String object is not created for a String variable until…
6) Define the String Methods:
a. length()
b. charAt(index)
c. toLowerCase()
d. toUpperCase()
Scope
 Every variable has scope.
o Scope refers to where in a program an entity can be accessed by name.
o 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.
o 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.
o The scope of a local variable begins where they were declared and
ends at the end of the method in which they were declared.
o Also, you cannot have two local variables with the same name in the
same scope
Scope Example (What problems do you see?)
//Scope - shows an example of a local variable being used out of its scope // and with another
variable with the same name being in the same scope public class Scope {
public static void main(String[] args) {
x = 11;
int x;
System.out.println(x);
int x = 15;
System.out.println(x);
}
}
Rules for Comments
 Internal Documentation takes the form of Comments in Java.
o A Comment is…
 line(s) in a program that is ignored by the compiler entirely.
o 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
o 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. (Not demonstrated here)

Your comments should do three things at this point
o
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 program does
o
Give information about what segments of code do in the program, 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.
o
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
//--------------------------------------
Programming Example of Comments.
/*************************************************************
* Author: Mr. O’Hara
* Course: CS0007
* Date Created: 5/25/2011
*Description: This file holds the triangle stats program, which computes the
* perimeter and area of a triangle with sides of length 2.3, 5.9, and 7.2, then
* displays the lengths of the sides, the perimeter and the area to the screen
***********************************************************/
public class Commenting {
public static void main(String[] args) {
//Declarations for the sides, the perimeter, the area, and the
//semiperimeter s
double side1 = 2.3, side2 = 5.9, side3 = 7.2, perimeter, s, area;
perimeter = side1 + side2 + side3;//Computes the perimeter
s = perimeter/2; //Computes the semiperimeter
//Computes the area
area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
//Displays the triangle's sides, the perimeter, and the area to the screen
System.out.print("The lengths of the triangle's sides are " + side1);
System.out.println(", " + side2 + ", " + side3 + ".");
System.out.println("The perimeter of the triangle is " + perimeter );
System.out.println("The area of the triangle is " + area );
}
}
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.
o This has NOTHING to do with syntax.
o 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);}}
o It even compiles and runs, but its really difficult to read.
 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;
…
}
}
o 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.
o Also note that the closing braces are in the same column as their headers.
 Rule 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
 We’ve also went over some naming conventions:
o Self-documenting code
o Classes start with a capital letter
o Variables start with a lowercase letter
o 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 = new Scanner(System.in);
o Scanner keyboard declares a variable named keyboard that is type
Scanner.
 Because Scanner is a class, keyboard is a reference variable.
o = is the assignment operator, so we are initializing the keyboard variable.
o new is a Java keyword that creates an object in memory, what follows it tells the
compiler what object is to be created.
o 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.
o We will talk more about constructors much later in the course.
o The result is that we have a reference variable, keyboard, that references a
scanner object that is associated with standard input.
 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.
o 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;
o This tells the compiler where to find the definition for the Scanner class
 The Scanner class provides methods for reading input as different types:
o nextByte() – Returns input as a byte
o nextDouble() – Returns input a double
o nextFloat() – Returns input as a float
o nextInt() – Returns input as an int
o nextLine() – Returns input as a String
o nextLong() – Returns input as a long
o nextShort() – Returns input as a short
o 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.
o 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.
import java.util.Scanner; //Needed for the Scanner class
/**
* This program demonstrates the use of the Scanner class
*/
public class Scanner1 {
public static void main(String[] args) {
String name;
int hours;
double payRate;
double grossPay;
//creates a scanner object to read standard input
Scanner input = new Scanner(System.in);
//Get the user's name
System.out.print("Enter your name: ");
name = input.nextLine();
//Get the number of hours worked this week
//ASSUMES INTEGER INPUT
System.out.print("Enter the number of hours you've worked this” +
week: ");
hours = input.nextInt();
//Get the user's hourly pay rate
System.out.print("Enter your hourly pay rate: ");
payRate = input.nextDouble();
//Calculate Gross Pay
grossPay = hours * payRate;
//Display the resulting information
System.out.println("Hello, " + name);
System.out.println("Your gross pay is $" + grossPay);
}
}
import java.util.Scanner;
/**
* This programs shows how to take a single character as input
*/
public class ReadCharacter {
public static void main(String[] args) {
String input;
//Holds the input
char answer;
//Holds a single character
//Creates a scanner object with standard input
Scanner keyboard = new Scanner(System.in);
//Ask the user a question
System.out.print("Is your name Eric (Y=yes, N=no)? ");
input = keyboard.nextLine(); //Get the user's input
answer = input.charAt(0); //Gets the 1st char from the input
System.out.println("The user entered " + answer);
}
}
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.
INPUT PROBLEM
import java.util.Scanner;
/**
* This program demonstrates the problem with using nextLine after
* another Scanner method
*/
public class InputProblem {
public static void main(String[] args) {
String name;
int hours;
double payRate;
double grossPay;
//creates a scanner object to read standard input
Scanner input = new Scanner(System.in);
//Get the number of hours worked this week
//ASSUMES INTEGER INPUT
System.out.print("Enter the number of hours you've worked” +
“ this week: ");
hours = input.nextInt();
//Get the user's hourly pay rate
System.out.print("Enter your hourly pay rate: ");
payRate = input.nextDouble();
//Get the user's name
System.out.print("Enter your name: ");
name = input.nextLine();
//Calculate Gross Pay
grossPay = hours * payRate;
//Display the resulting information
System.out.println("Hello, " + name);
System.out.println("Your gross pay is $" + grossPay);
}
}
Corrected Input Problem
import java.util.Scanner;
/**
* This program demonstrates a solution to the problem with
using nextLine
* after another Scanner method
*/
public class CorrectedInputProblem {
public static void main(String[] args) {
String name;
int hours;
double payRate;
double grossPay;
//creates a scanner object to read standard input
Scanner input = new Scanner(System.in);
//Get the number of hours worked this week
//ASSUMES INTEGER INPUT
System.out.print("Enter the number of hours you've” +
“worked this week: ");
hours = input.nextInt();
//Get the user's hourly pay rate
System.out.print("Enter your hourly pay rate: ");
payRate = input.nextDouble();
//THIS FIXES THE PROBLEM
input.nextLine();
//Get the user's name
System.out.print("Enter your name: ");
name = input.nextLine();
//Calculate Gross Pay
grossPay = hours * payRate;
//Display the resulting information
System.out.println("Hello, " + name);
System.out.println("Your gross pay is $" + grossPay);
}
}