content from MIT-cs106A
枚举,接口,搜索算法,标准库
课程内容:163
/**
* The Student class keeps track of the following pieces of data
* about a student: the student's name, ID number, and the number
* of credits the student has earned toward graduation.
* All of this information is entirely private to the class.
* Clients can obtain this information only by using the various
* methods defined by the class.
*/
public class Student {
/* Public constants */
/** The number of units required for graduation */
public static final double UNITS_TO_GRADUATE = 180.0;
/**
* Creates a new Student object with the specified name and ID.
* @param studentName The student's name as a String
* @param studentID The student's ID number as an int
*/
public Student(String studentName, int studentID) {
name = studentName;
ID = studentID;
}
/**
* Gets the name of this student.
* @return The name of this student
*/
public String getName() {
return name;
}
/**
* Gets the ID number of this student.
* @return The ID number of this student
*/
public int getID() {
return ID;
}
/**
* Sets the number of units earned.
* @param units The new number of units earned
*/
public void setUnits(double units) {
unitsEarned = units;
}
/**
* Gets the number of units earned.
* @return The number of units this student has earned
*/
public double getUnits() {
return unitsEarned;
}
/**
* Increments the number of units earned.
* @param additionalUnits The additional number of units earned
*/
public void incrementUnits(double additionalUnits) {
unitsEarned += additionalUnits;
}
/**
* Gets the number of units earned.
* @return Whether the student has enough units to graduate
*/
public boolean hasEnoughUnits() {
return (unitsEarned >= UNITS_TO_GRADUATE);
}
/**
* Creates a string identifying this student.
* @return The string used to display this student
*/
public String toString() {
return name + " (#" + ID + ")";
}
/* Private instance variables */
private String name; /* The student's name */
private int ID; /* The student's ID number */
private double unitsEarned; /* The number of units earned */
}
/**
* File: Stanford.java
* -------------------
* The program provides an example of using Student objects
*/
import acm.program.*;
public class Stanford extends ConsoleProgram {
/* Constants */
private static final int CS106A_UNITS = 5;
public void run() {
setFont("Times New Roman-28");
Student mehran = new Student("Mehran Sahami", 38000000);
mehran.setUnits(3);
printUnits(mehran);
Student nick = new Student("Nick Troccoli", 57000000);
nick.setUnits(179);
printUnits(nick);
println("Called tryToAddUnits to add to Nick's units...");
tryToAddUnits(nick.getUnits(), CS106A_UNITS);
printUnits(nick);
takeCS106A(mehran);
takeCS106A(nick);
printUnits(mehran);
printUnits(nick);
}
/**
* Prints the name and number of units that student s has,
* as well as whether the student can graduate
* @param s The student who we will print information for
*/
private void printUnits(Student s) {
println(s.getName() + " has " + s.getUnits() + " units");
println(s.toString() + " can graduate: " + s.hasEnoughUnits());
}
/**
* BUGGY!! -- Tries to add to numUnits, but only adds to copy!
* @param numUnits Original number of units
* @param numUnitsToAdd Number of units to add to original
*/
private void tryToAddUnits(double numUnits, double numUnitsToAdd) {
numUnits += numUnitsToAdd;
}
/**
* States that student s takes CS106A and increments number of units
* @param s The student who will be taking CS106A
*/
private void takeCS106A(Student s) {
println(s.getName() + " takes CS106A!!");
s.incrementUnits(CS106A_UNITS);
}
}
file reading
file reading example
file reading code for example
/*
* FilesExample.java
* -----------------
* This program shows an example of reading a file.
*/
/*
line==null can be put in while()
String line = rd.readLine();
while(line!=null) println();
*/
import acm.program.*;
import acm.util.*;
import java.io.*;
public class FilesExamples extends ConsoleProgram {
public void run() {
setFont("Times New Roman-24");
try {
BufferedReader rd = new BufferedReader(new FileReader("claire.txt"));
while (true) {
String line = rd.readLine();
if (line == null) break;
println("Read line: [" + line + "]");
}
rd.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
/*
* AnotherFileExample.java
* -----------------------
* This program shows an example of reading a file.
*/
/*
open or create file in a method, two try-catch, convenient for debugging
*/
import acm.program.*;
import acm.util.*;
import java.io.*;
public class AnotherFileExample extends ConsoleProgram {
public void run() {
setFont("Times New Roman-24");
BufferedReader rd = openFile("Please enter filename: ");
try {
while (true) {
String line = rd.readLine();
if (line == null) break;
println("Read line: [" + line + "]");
}
rd.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
}
private BufferedReader openFile(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String filename = readLine(prompt);
rd = new BufferedReader(new FileReader(filename));
} catch (IOException ex) {
println("Can't open that file, chief.");
}
}
return rd;
}
}
/*
* CopyFile.java
* -------------
* This program shows an example of copying a text file
* line by line.
*/
import acm.program.*;
import acm.util.*;
import java.io.*;
public class CopyFile extends ConsoleProgram {
public void run() {
setFont("Times New Roman-24");
BufferedReader rd = openFile("Please enter filename: ");
try {
PrintWriter wr = new PrintWriter(new FileWriter("copy.txt"));
while (true) {
String line = rd.readLine();
if (line == null) break;
println(line); // console
wr.println(line); // file
}
rd.close();
wr.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
}
private BufferedReader openFile(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String filename = readLine(prompt);
rd = new BufferedReader(new FileReader(filename));
} catch (IOException ex) {
println("Nice try punk. That file doesn't exist.");
}
}
return rd;
}
}
/*
* SimpleArrayListExample.java
* ---------------------------
* This program shows an example of using an ArrayList.
*/
import acm.program.*;
import java.util.*;
public class SimpleArrayListExample extends ConsoleProgram {
public void run() {
setFont("Courier New-bold-24");
ArrayList<String> strList = new ArrayList<String>();
readStringList(strList);
printArrayList(strList);
ArrayList<Integer> intList = new ArrayList<Integer>();
readIntList(intList);
printArrayList(intList);
}
private void readStringList(ArrayList<String> list) {
while (true) {
String line = readLine("Next line: ");
if (line.equals("")) break;
list.add(line);
}
}
private void printArrayList(ArrayList list) {
println("List contains " + list.size() + " elements");
for(int i = 0; i < list.size(); i++) {
println(list.get(i)); // unboxes value if needed (e.g., int)
}
}
private void readIntList(ArrayList<Integer> list) {
while (true) {
int value = readInt("Next integer (-1 to stop): ");
if (value == -1) break;
list.add(value); // boxes value (int) to Integer
}
}
}
/*
* IntegerArrayListExample.java
* ---------------------------
* This program shows an example of using an Integer ArrayList.
*/
import acm.program.*;
import java.util.*;
public class IntegerArrayListExample extends ConsoleProgram {
public void run() {
setFont("Courier New-bold-24");
ArrayList<Integer> intList = new ArrayList<Integer>();
readList(intList);
printArrayList(intList);
readList(intList);
printArrayList(intList);
}
private void readList(ArrayList<Integer> list) {
while (true) {
int value = readInt("Next number: ");
if (value == -1) break;
list.add(value); // boxes value (int) to Integer
}
}
private void printArrayList(ArrayList list) {
println("List contains " + list.size() + " elements");
for(int i = 0; i < list.size(); i++) {
println(list.get(i)); // unboxes Integer to int
}
}
}
/*
* File: AverageScores.java
* ------------------------
* This program shows an example of using arrays.
*/
import acm.program.*;
public class AverageScores extends ConsoleProgram {
private static final int SENTINEL = -1;
private static final int MAX_SCORES = 1000; // actual size
public void run() {
setFont("Courier New-bold-24");
int[] midtermScores = new int[MAX_SCORES];
int numScores = 0; // effective size
while (true) {
int score = readInt("Score: ");
if (score == SENTINEL) break;
midtermScores[numScores++] = score;
}
double averageScore = computeAverage(midtermScores, numScores);
println("Average score: " + averageScore);
}
private double computeAverage(int[] arr, int numScores) {
double average = 0;
for(int i = 0; i < numScores; i++) {
average += arr[i];
}
average = average / numScores;
return average;
}
}
/*
* SwapExample.java
* -----------------
* This program shows an example of using arrays when swapping values.
*/
import acm.program.*;
public class SwapExample extends ConsoleProgram {
public void run() {
setFont("Courier New-bold-24");
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
println("Buggy swap results:");
swapElementsBuggy(array[0], array[1]);
println("array[0] = " + array[0]);
println("array[1] = " + array[1]);
println("Happy swap results:");
swapElementsHappy(array, 0, 1);
println("array[0] = " + array[0]);
println("array[1] = " + array[1]);
}
private void swapElementsBuggy(int x, int y) {
int temp = x;
x = y;
y = temp;
}
private void swapElementsHappy(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
/*
* File: TwoDimensionalArrayExample.java
* -------------------------------------
* This program shows an example of using 2-dimensional arrays.
*/
import acm.program.*;
public class TwoDimensionalArrayExample extends ConsoleProgram {
public static final int ROWS = 2;
public static final int COLS = 3;
public void run() {
setFont("Courier New-bold-24");
int[][] arr = new int[ROWS][COLS];
initMatrix(arr);
printMatrix(arr);
}
private void initMatrix(int[][] matrix) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = j;
}
}
}
private void printMatrix(int[][] matrix) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
print(matrix[i][j] + " ");
}
println();
}
}
}
import acm.program.*;
public class TestScores extends ConsoleProgram {
// Maximum number of students in a course
private static final int MAX_STUDENTS = 1000;
public void run() {
setFont("Times New Roman-24");
int numScores = readInt("Number of scores per student: ");
scores = new int[MAX_STUDENTS][numScores];
initScores();
println("Scores[0] before increment");
printList(scores[0]);
incrementScoreList(scores[0]);
println("Scores[0] after increment");
printList(scores[0]);
}
// Initialized score grid to all be 0
private void initScores() {
for(int i = 0; i < scores.length; i++) {
for(int j = 0; j < scores[0].length; j++) {
scores[i][j] = 0;
}
}
}
// Prints every element of list on a separate line
private void printList(int[] list) {
for(int i = 0; i < list.length; i++) {
println(list[i]);
}
}
// Adds 1 to every element of list
private void incrementScoreList(int[] list) {
for(int i = 0; i < list.length; i++) {
list[i]++;
}
}
/* private instance variable */
private int[][] scores;
}
/*
* File: HashMapExample.java
* -------------------------
* This program shows an example of using a HashMap to keep
* track of a simple phonebook (mapping names to phone numbers).
*/
import acm.program.*;
import java.util.*;
public class HashMapExample extends ConsoleProgram {
public void run() {
setFont("Times New Roman-24");
println("Reading in phone numbers");
readPhoneNumbers();
println("Displaying phone numbers");
displayAllNumbers();
println("Looking up phone numbers");
lookUpNumbers();
}
// Ask the user for phone numbers to store in phonebook.
private void readPhoneNumbers() {
while (true) {
String name = readLine("Enter name: ");
if (name.equals("")) break;
int number = readInt("Phone number (as int): ");
phonebook.put(name, number);
}
}
// Print out all the names/phone numbers in the phonebook.
// (This version of the method uses iterators.)
private void displayAllNumbers() {
Iterator<String> it = phonebook.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
Integer number = phonebook.get(name);
println(name + ": " + number);
}
}
// Print out all the names/phone numbers in the phonebook.
// (This version of the method uses a foreach loop.)
private void displayAllNumbers2() {
for(String name : phonebook.keySet()) {
Integer number = phonebook.get(name);
println(name + ": " + number);
}
}
// Allow the user to lookup phone numbers in the phonebook
// by looking up the number associated with a name.
private void lookUpNumbers() {
while (true) {
String name = readLine("Enter name to lookup: ");
if (name.equals("")) break;
Integer number = phonebook.get(name);
if (number == null) {
println(name + " not in phonebook");
} else {
println(number);
}
}
}
/* Private instance variable */
private Map<String,Integer> phonebook = new HashMap<String,Integer>();
}
屏幕快照 2016-12-26 上午4.58.26.png
屏幕快照 2016-12-26 上午5.02.58.png
屏幕快照 2016-12-26 上午5.03.07.png
primitives passes by value
屏幕快照 2016-12-26 上午7.03.59.png
instance variables
屏幕快照 2016-12-26 上午7.06.53.png
屏幕快照 2016-12-26 上午7.07.40.png
屏幕快照 2016-12-26 上午7.08.44.png
屏幕快照 2016-12-26 上午7.12.10.png 屏幕快照 2016-12-26 下午5.54.44.png
屏幕快照 2016-12-26 下午5.54.51.png
屏幕快照 2016-12-26 上午7.22.42.png
屏幕快照 2016-12-26 上午7.39.40.png
屏幕快照 2016-12-26 上午7.39.48.png
屏幕快照 2016-12-26 上午7.40.00.png
屏幕快照 2016-12-26 上午7.41.18.png
屏幕快照 2016-12-26 上午7.41.29.png
屏幕快照 2016-12-26 上午7.41.38.png
屏幕快照 2016-12-26 上午7.41.46.png
网友评论