cs106A-MIT-过滤掉了图形部分

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,116评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,656评论 18 139
  • 楼上不知哪家邻居,近几个月开始学弹钢琴,我上班在弹,下班了也在弹,日出而作,日落还作,一直在轻轻的弹,轻轻的练,虽...
    爱跑步的小懒阅读 1,072评论 0 0
  • 诉说一个人的倾听,想起全国际的自己,问此生,多少缘,多少自己,国际那么大,人生那么远,谁是谁的谁,错失就是终身,失...
    mikasi35阅读 316评论 0 0
  • 时间不停流转,冷眼观看灯火从明亮闪烁到消失殆尽的循环。金属制成的小针在钟盘里按部就班的朝着前面的每个刻度一步一步挪...
    爱笑的鱼613阅读 645评论 0 3