📣 Back to School开学季 - VIP通行证5折优惠!蓝莓、Offer多多同步优惠
查看: 6369| 回复: 11
跳转到指定楼层
上一主题 下一主题
收起左侧

Stanford CS106A #6 Assignment6讨论帖

全局:
本帖最后由 yiyiyaya 于 2012-8-18 10:37 编辑

时间:2012.8.18-2012.8.21

课程:
20. Swing Interactors, the JComponent Hierarchy
21. GUI, Interactors
22.  Data-driven programs

作业:
Assignment 5 NameServer.java
due: 2012.8.21


单选投票, 共有 14 人参与投票
您所在的用户组没有投票权限

评分

参与人数 1大米 +3 收起 理由
LLLLLin + 3 给你点个赞!

查看全部评分


上一篇:我也来贴一个公开课的网站~
下一篇:Stanford CS106A #7 Assignment7 讨论帖
🔗
jasonilove 2012-8-18 11:15:38 | 只看该作者
全局:
BackgroundGrill(自己建的一个class)
  1. import acm.graphics.*;
  2. public class BackgroundGrill extends GCompound
  3.         implements NameSurferConstants{
  4.         public BackgroundGrill(int width,int height){
  5.                 add(new GLine(0,GRAPH_MARGIN_SIZE,width,GRAPH_MARGIN_SIZE));
  6.                 add(new GLine(0,height-GRAPH_MARGIN_SIZE,width,height-GRAPH_MARGIN_SIZE));
  7.                 for(int i=0;i<NDECADES;i++){
  8.                         int x=(width/NDECADES)*(i+1);
  9.                         add(new GLine(x,0,x,height));
  10.                 }
  11.         }

  12. }
复制代码
NameSurferDataBase
  1. import java.io.*;
  2. import java.util.*;
  3. import acm.util.*;

  4. public class NameSurferDataBase implements NameSurferConstants {
  5.        
  6. /* Constructor: NameSurferDataBase(filename) */
  7. /**
  8. * Creates a new NameSurferDataBase and initializes it using the
  9. * data in the specified file.  The constructor throws an error
  10. * exception if the requested file does not exist or if an error
  11. * occurs as the file is being read.
  12. */
  13.         public NameSurferDataBase(String filename) {
  14.                 try{
  15.                         BufferedReader br=new BufferedReader(new FileReader(filename));
  16.                         while(true){
  17.                                 String str=br.readLine();
  18.                                 if(str==null){
  19.                                         break;
  20.                                 }
  21.                                 NameSurferEntry nse=new NameSurferEntry(str);
  22.                                 dataBase.put(nse.getName(),nse);
  23.                         }
  24.                         br.close();
  25.                 }
  26.                 catch(IOException e){
  27.                         throw new ErrorException(e);
  28.                 }
  29.         }
  30.        
  31. /* Method: findEntry(name) */
  32. /**
  33. * Returns the NameSurferEntry associated with this name, if one
  34. * exists.  If the name does not appear in the database, this
  35. * method returns null.
  36. */
  37.         public NameSurferEntry findEntry(String name) {
  38.                 if(name.charAt(0)>='a'&&name.charAt(0)<='z'){
  39.                         char x=(char)(name.charAt(0)+'A'-'a');
  40.                         name=x+name.substring(1);
  41.                 }
  42.                 for(int i=1;i<name.length();i++){
  43.                         if(name.charAt(i)>='A'&&name.charAt(i)<='Z'){
  44.                                 char x=(char)(name.charAt(i)+'a'-'A');
  45.                                 name=name.substring(0, i)+x+name.substring(i+1);
  46.                         }
  47.                 }
  48.                 if(dataBase.containsKey(name)){
  49.                         return dataBase.get(name);
  50.                 }
  51.                 // You need to turn this stub into a real implementation //
  52.                 return null;
  53.         }
  54.         private HashMap<String,NameSurferEntry> dataBase=new HashMap<String,NameSurferEntry>();
  55. }
复制代码
NameSurferEntry
  1. import acm.util.*;
  2. import java.util.*;

  3. public class NameSurferEntry implements NameSurferConstants {

  4. /* Constructor: NameSurferEntry(line) */
  5. /**
  6. * Creates a new NameSurferEntry from a data line as it appears
  7. * in the data file.  Each line begins with the name, which is
  8. * followed by integers giving the rank of that name for each
  9. * decade.
  10. */
  11.         public NameSurferEntry(String line) {
  12.                 StringTokenizer strtk=new StringTokenizer(line);
  13.                 name=strtk.nextToken();
  14.                 ranks=new int[NDECADES];
  15.                 for(int i=0;i<NDECADES;i++){
  16.                         ranks[i]=Integer.parseInt(strtk.nextToken());
  17.                 }
  18.                
  19.         }

  20. /* Method: getName() */
  21. /**
  22. * Returns the name associated with this entry.
  23. */
  24.         public String getName() {
  25.                 return name;
  26.         }

  27. /* Method: getRank(decade) */
  28. /**
  29. * Returns the rank associated with an entry for a particular
  30. * decade.  The decade value is an integer indicating how many
  31. * decades have passed since the first year in the database,
  32. * which is given by the constant START_DECADE.  If a name does
  33. * not appear in a decade, the rank value is 0.
  34. */
  35.         public int getRank(int decade) {
  36.                
  37.                 return ranks[(decade-1900)/10];
  38.         }

  39. /* Method: toString() */
  40. /**
  41. * Returns a string that makes it easy to see the value of a
  42. * NameSurferEntry.
  43. */
  44.         public String toString() {
  45.                
  46.                 return name+" ["+ranks[0]+" "+ranks[1]+" "+ranks[2]+" "+ranks[3]+" "+ranks[4]+" "+ranks[5]+" "+ranks[6]+" "+ranks[7]+" "+ranks[8]+" "+ranks[9]+" "+ranks[10]+" ]";
  47.         }
  48.         private String name;
  49.         private int[] ranks;
  50. }
复制代码
NameSurferGraph
  1. import acm.graphics.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import java.awt.*;

  5. import com.sun.org.apache.xerces.internal.xs.StringList;

  6. public class NameSurferGraph extends GCanvas
  7.         implements NameSurferConstants, ComponentListener {

  8.         /**
  9.         * Creates a new NameSurferGraph object that displays the data.
  10.         */
  11.         public NameSurferGraph() {
  12.                
  13.                 addComponentListener(this);
  14.                 grill=new BackgroundGrill(getWidth(),getHeight());
  15.                 add(grill,0,0);
  16.                 label=new GLabel[NDECADES];
  17.                 for(int i=0;i<NDECADES;i++){
  18.                         int year=1900+i*10;
  19.                         label[i]=new GLabel(String.valueOf(year),i*getWidth()/NDECADES,getHeight());
  20.                         add(label[i]);
  21.                 }
  22.         }
  23.        
  24.         /**
  25.         * Clears the list of name surfer entries stored inside this class.
  26.         */
  27.         public void clear() {
  28.                 removeAll();
  29.                 grill=new BackgroundGrill(getWidth(),getHeight());
  30.                 add(grill);
  31.                 for(int i=0;i<NDECADES;i++){
  32.                         label[i].setLocation(i*getWidth()/NDECADES,getHeight());
  33.                         add(label[i]);
  34.                 }
  35.                 list.removeAll(list);
  36.                 labelOfEmpty=null;
  37.                
  38.         }
  39.        
  40.         /* Method: addEntry(entry) */
  41.         /**
  42.         * Adds a new NameSurferEntry to the list of entries on the display.
  43.         * Note that this method does not actually draw the graph, but
  44.         * simply stores the entry; the graph is drawn by calling update.
  45.         */
  46.         public void addEntry(NameSurferEntry entry) {
  47.                 if(labelOfEmpty!=null){
  48.                         remove(labelOfEmpty);
  49.                         labelOfEmpty=null;
  50.                 }
  51.                 if(entry.getRank(1900)==-1){
  52.                         labelOfEmpty=new GLabel(entry.getName()+" is not in the database.",0,GRAPH_MARGIN_SIZE);
  53.                         add(labelOfEmpty);
  54.                 }
  55.                 else{
  56.                         list.add(entry);
  57.                 drawTheLines(entry);
  58.                 }               
  59.         }
  60.        

  61.         private void drawTheLines(NameSurferEntry entry){
  62.                 int[] x=new int[NDECADES];
  63.                 int[] y=new int[NDECADES];
  64.                 for(int i=0;i<NDECADES;i++){
  65.                         x[i]=(getWidth()/NDECADES)*i;
  66.                         y[i]=entry.getRank(1900+i*10)*(getHeight()-2*GRAPH_MARGIN_SIZE)/1000+GRAPH_MARGIN_SIZE;
  67.                         if(entry.getRank(1900+i*10)==0){
  68.                                 y[i]=getHeight()-GRAPH_MARGIN_SIZE;
  69.                         }
  70.                 }
  71.                
  72.                 Color co=colorOfItem(list.indexOf(entry));
  73.                
  74.                 for(int i=0;i<NDECADES-1;i++){
  75.                         GLine line=new GLine(x[i],y[i],x[i+1],y[i+1]);
  76.                         int rank=entry.getRank(1900+i*10);
  77.                         if(rank==0){
  78.                                 GLabel label=new GLabel(entry.getName()+"*",x[i],y[i]);
  79.                                 line.setColor(co);
  80.                                 label.setColor(co);
  81.                                 add(line);
  82.                                 add(label);
  83.                         }
  84.                         else{
  85.                                 GLabel label=new GLabel(entry.getName()+entry.getRank(1900+i*10),x[i],y[i]);
  86.                                 line.setColor(co);
  87.                                 label.setColor(co);
  88.                                 add(line);
  89.                                 add(label);
  90.                         }
  91.                 }
  92.                 int rank=entry.getRank(2000);
  93.                 if(rank==0){
  94.                         GLabel label=new GLabel(entry.getName()+"*",x[NDECADES-1],y[NDECADES-1]);
  95.                         label.setColor(co);
  96.                         add(label);
  97.                 }
  98.                 else{
  99.                         GLabel label=new GLabel(entry.getName()+entry.getRank(2000),x[NDECADES-1],y[NDECADES-1]);
  100.                         label.setColor(co);
  101.                         add(label);
  102.                 }
  103.         }
  104.        
  105.         private Color colorOfItem(int i){
  106.                 switch(i%4){
  107.                 case 0:return Color.BLACK;
  108.                 case 1:return Color.RED;
  109.                 case 2:return Color.BLUE;
  110.                 default:return Color.MAGENTA;
  111.                 }
  112.         }
  113.        
  114.        
  115.         /**
  116.         * Updates the display image by deleting all the graphical objects
  117.         * from the canvas and then reassembling the display according to
  118.         * the list of entries. Your application must call update after
  119.         * calling either clear or addEntry; update is also called whenever
  120.         * the size of the canvas changes.
  121.         */
  122.         public void update() {
  123.                 removeAll();
  124.                 grill=new BackgroundGrill(getWidth(),getHeight());
  125.                 add(grill);
  126.                 for(int i=0;i<NDECADES;i++){
  127.                         label[i].setLocation(i*getWidth()/NDECADES,getHeight());
  128.                         add(label[i]);
  129.                 }
  130.                 for(int i=0;i<list.size();i++){
  131.                         drawTheLines(list.get(i));
  132.                 }
  133.         }
  134.        
  135.        
  136.        
  137.        
  138.         /* Implementation of the ComponentListener interface */
  139.         public void componentHidden(ComponentEvent e) { }
  140.         public void componentMoved(ComponentEvent e) { }
  141.         public void componentResized(ComponentEvent e) { update(); }
  142.         public void componentShown(ComponentEvent e) { }
  143.        
  144.         private BackgroundGrill grill;
  145.         private GLabel[] label;
  146.         private ArrayList<NameSurferEntry> list=new ArrayList<NameSurferEntry>();
  147.         private GLabel labelOfEmpty=null;
  148. }
复制代码
NameSurfer
  1. import acm.program.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;

  4. public class NameSurfer extends Program implements NameSurferConstants {
  5.        
  6.         public static void main(String[] args){
  7.                 new NameSurfer().start(args);
  8.         }

  9. /* Method: init() */
  10. /**
  11. * This method has the responsibility for reading in the data base
  12. * and initializing the interactors at the bottom of the window.
  13. */
  14.         public void init() {
  15.                 dataBase=new NameSurferDataBase(NAMES_DATA_FILE);
  16.             add(new JLabel("Name"),SOUTH);
  17.             tf=new JTextField(20);
  18.             tf.setActionCommand("Graph");
  19.             tf.addActionListener(this);
  20.             add(tf,SOUTH);
  21.             add(new JButton("Graph"),SOUTH);
  22.             add(new JButton("Clear"),SOUTH);
  23.             addActionListeners();
  24.             graph=new NameSurferGraph();
  25.             add(graph);
  26.             
  27.         }

  28. /* Method: actionPerformed(e) */
  29. /**
  30. * This class is responsible for detecting when the buttons are
  31. * clicked, so you will have to define a method to respond to
  32. * button actions.
  33. */
  34.         public void actionPerformed(ActionEvent e) {
  35.                 if(e.getActionCommand().equals("Graph")){
  36.                         if(dataBase.findEntry(tf.getText())!=null){
  37.                                 graph.addEntry(dataBase.findEntry(tf.getText()));
  38.                         }
  39.                         if(dataBase.findEntry(tf.getText())==null){
  40.                                 NameSurferEntry entry=new NameSurferEntry(tf.getText()+" -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1");
  41.                                 graph.addEntry(entry);
  42.                         }
  43.                 }
  44.                 if(e.getActionCommand().equals("Clear")){
  45.                         graph.clear();
  46.                 }
  47.         }
  48.        
  49.         private JTextField tf;
  50.         private NameSurferDataBase dataBase;
  51.         private NameSurferGraph graph;
  52.        
  53. }
复制代码
回复

使用道具 举报

🔗
zhuolinliu8 2012-8-18 11:28:19 | 只看该作者
全局:
NameSurfer.java
  1. /*
  2. * File: NameSurfer.java
  3. * ---------------------
  4. * When it is finished, this program will implements the viewer for
  5. * the baby-name database described in the assignment handout.
  6. */

  7. import acm.program.*;
  8. import java.awt.event.*;
  9. import javax.swing.*;

  10. public class NameSurfer extends Program implements NameSurferConstants {

  11.         /* Method: init() */
  12.         /**
  13.          * This method has the responsibility for reading in the data base
  14.          * and initializing the interactors at the top of the window.
  15.          */
  16.         public void init() {
  17.                 /* Initialzing the interactors */
  18.                 add(new JLabel("Name"),SOUTH);
  19.                 input_name.setActionCommand("Graph");
  20.                 input_name.addActionListener(this);
  21.                 add(input_name,SOUTH);
  22.                
  23.                 add(new JButton("Graph"),SOUTH);
  24.                 add(new JButton("Clear"),SOUTH);
  25.                 addActionListeners();
  26.                
  27.                 /* Canvas initiating */
  28.                 canvas = new NameSurferGraph();
  29.                 add(canvas);
  30.         }

  31.         /* Method: actionPerformed(e) */
  32.         /**
  33.          * This class is responsible for detecting when the buttons are
  34.          * clicked, so you will have to define a method to respond to
  35.          * button actions.
  36.          */
  37.         public void actionPerformed(ActionEvent e) {
  38.                 String cmd = e.getActionCommand();
  39.                
  40.                 if(cmd.equals("Graph")){
  41.                         NameSurferEntry temp = nsData.findEntry(input_name.getText());
  42.                         if(temp != null)
  43.                                 canvas.addEntry(temp);
  44.                         //else println("No Such Name!");
  45.                 }else if(cmd.equals("Clear")) canvas.clear();
  46.         }
  47.        
  48.         /** TextField initiate */
  49.         private JTextField input_name = new JTextField(20);
  50.         private NameSurferDataBase nsData = new NameSurferDataBase(NAMES_DATA_FILE);
  51.         private NameSurferGraph canvas;
  52. }
复制代码
NameSurferConstants.java
  1. /*
  2. * File: NameSurferConstants.java
  3. * ------------------------------
  4. * This file declares several constants that are shared by the
  5. * different modules in the NameSurfer application.  Any class
  6. * that implements this interface can use these constants.
  7. */

  8. public interface NameSurferConstants {

  9.         /** The width of the application window */
  10.         public static final int APPLICATION_WIDTH = 800;

  11.         /** The height of the application window */
  12.         public static final int APPLICATION_HEIGHT = 600;

  13.         /** The name of the file containing the data */
  14.         public static final String NAMES_DATA_FILE = "names-data.txt";

  15.         /** The first decade in the database */
  16.         public static final int START_DECADE = 1900;

  17.         /** The number of decades */
  18.         public static final int NDECADES = 12;

  19.         /** The maximum rank in the database */
  20.         public static final int MAX_RANK = 1000;

  21.         /** The number of pixels to reserve at the top and bottom */
  22.         public static final int GRAPH_MARGIN_SIZE = 20;

  23. }
复制代码
NameSurferDataBase.java
  1. /*
  2. * File: NameSurferDataBase.java
  3. * -----------------------------
  4. * This class keeps track of the complete database of names.
  5. * The constructor reads in the database from a file, and
  6. * the only public method makes it possible to look up a
  7. * name and get back the corresponding NameSurferEntry.
  8. * Names are matched independent of case, so that "Eric"
  9. * and "ERIC" are the same names.
  10. */
  11. import java.io.*;
  12. import java.util.*;

  13. public class NameSurferDataBase implements NameSurferConstants {
  14.        
  15.         /* Constructor: NameSurferDataBase(filename) */
  16.         /**
  17.          * Creates a new NameSurferDataBase and initializes it using the
  18.          * data in the specified file.  The constructor throws an error
  19.          * exception if the requested file does not exist or if an error
  20.          * occurs as the file is being read.
  21.          */
  22.         public NameSurferDataBase(String filename) {
  23.                 BufferedReader rd = null;
  24.                
  25.                 try{
  26.                         rd = new BufferedReader(new FileReader(filename));
  27.                         NameSurferEntry nse;
  28.                         String line = rd.readLine();
  29.                         while(line != null){
  30.                                 nse = new NameSurferEntry(line);
  31.                                 line = rd.readLine();
  32.                                 database.put(nse.getName(),nse);
  33.                         }
  34.                         rd.close();
  35.                 } catch (IOException ex){System.out.println("NO FILE!");}
  36.         }
  37.        
  38.         /* Method: findEntry(name) */
  39.         /**
  40.          * Returns the NameSurferEntry associated with this name, if one
  41.          * exists.  If the name does not appear in the database, this
  42.          * method returns null.
  43.          */
  44.         public NameSurferEntry findEntry(String name) {
  45.                 if(database.containsKey(name))
  46.                         return database.get(name);
  47.                 return null;
  48.         }
  49.        
  50.         private HashMap<String, NameSurferEntry> database = new HashMap<String,NameSurferEntry>();
  51. }

复制代码
NameSurferEntry.java
  1. /*
  2. * File: NameSurferEntry.java
  3. * --------------------------
  4. * This class represents a single entry in the database.  Each
  5. * NameSurferEntry contains a name and a list giving the popularity
  6. * of that name for each decade stretching back to 1900.
  7. */

  8. import acm.util.*;
  9. import java.util.*;

  10. public class NameSurferEntry implements NameSurferConstants {

  11.         /* Constructor: NameSurferEntry(line) */
  12.         /**
  13.          * Creates a new NameSurferEntry from a data line as it appears
  14.          * in the data file.  Each line begins with the name, which is
  15.          * followed by integers giving the rank of that name for each
  16.          * decade.
  17.          */
  18.         public NameSurferEntry(String line) {
  19.                 StringTokenizer token = new StringTokenizer(line);
  20.                 name = token.nextToken();
  21.                 for(int i=0; i<NDECADES; i++)
  22.                         rank[i] = Integer.parseInt(token.nextToken());
  23.         }

  24.         /* Method: getName() */
  25.         /**
  26.          * Returns the name associated with this entry.
  27.          */
  28.         public String getName() {
  29.                 return this.name;
  30.         }

  31.         /* Method: getRank(decade) */
  32.         /**
  33.          * Returns the rank associated with an entry for a particular
  34.          * decade.  The decade value is an integer indicating how many
  35.          * decades have passed since the first year in the database,
  36.          * which is given by the constant START_DECADE.  If a name does
  37.          * not appear in a decade, the rank value is 0.
  38.          */
  39.         public int getRank(int decade) {
  40.                 return this.rank[decade];
  41.         }

  42.         /* Method: toString() */
  43.         /**
  44.          * Returns a string that makes it easy to see the value of a
  45.          * NameSurferEntry.
  46.          */
  47.         public String toString() {
  48.                 String result = this.name + " [" + rank[0];
  49.                 for(int i=1; i<NDECADES; i++)
  50.                         result = result + " " + rank[i];
  51.                 result += "]";
  52.                 return result;
  53.         }
  54.        
  55.         /* Entry data */
  56.         private String name;
  57.         private int[] rank = new int[NDECADES];
  58. }

复制代码
NameSurferGraph.java
  1. /*
  2. * File: NameSurferGraph.java
  3. * ---------------------------
  4. * This class represents the canvas on which the graph of
  5. * names is drawn. This class is responsible for updating
  6. * (redrawing) the graphs whenever the list of entries changes
  7. * or the window is resized.
  8. */

  9. import acm.graphics.*;
  10. import acm.program.*;
  11. import java.awt.event.*;
  12. import java.util.*;
  13. import java.awt.*;
  14. import javax.swing.*;


  15. public class NameSurferGraph extends GCanvas
  16.         implements NameSurferConstants, ComponentListener {

  17.         /**
  18.          * Creates a new NameSurferGraph object that displays the data.
  19.          */
  20.         public NameSurferGraph() {
  21.                 addComponentListener(this);
  22.         }
  23.        
  24.        
  25.         /**
  26.          * Clears the list of name surfer entries stored inside this class.
  27.          */
  28.         public void clear() {
  29.                 int width = getWidth(), height = getHeight();
  30.                 int interval = width/NDECADES;
  31.                 removeAll();
  32.                 drawBackground(width,height,interval);
  33.                 entry_ar.clear();
  34.         }
  35.        
  36.        
  37.         /* Method: addEntry(entry) */
  38.         /**
  39.          * Adds a new NameSurferEntry to the list of entries on the display.
  40.          * Note that this method does not actually draw the graph, but
  41.          * simply stores the entry; the graph is drawn by calling update.
  42.          */
  43.         public void addEntry(NameSurferEntry entry) {
  44.                 entry_ar.add(entry);
  45.                 update();
  46.         }
  47.        
  48.        
  49.         /**
  50.          * Updates the display image by deleting all the graphical objects
  51.          * from the canvas and then reassembling the display according to
  52.          * the list of entries. Your application must call update after
  53.          * calling either clear or addEntry; update is also called whenever
  54.          * the size of the canvas changes.
  55.          */
  56.         public void update() {
  57.                 int width = getWidth(), height = getHeight();
  58.                 int interval = width/NDECADES;
  59.                 removeAll();
  60.                 drawBackground(width,height,interval);
  61.                
  62.                 /* Draw Entry */
  63.                 for(int entry=0; entry<entry_ar.size();entry++){
  64.                         Color color = getColor(entry);
  65.                         NameSurferEntry itn = entry_ar.get(entry);
  66.                         int rank = itn.getRank(0);
  67.                         if (rank == 0) rank = MAX_RANK; // Adjust Rank if there is no record.
  68.                         int y2 = (height-2*GRAPH_MARGIN_SIZE)* rank /MAX_RANK + GRAPH_MARGIN_SIZE;
  69.                        
  70.                         for(int i=0; i<NDECADES-1; i++){
  71.                                 int y1 = y2;
  72.                                 rank = itn.getRank(i+1);
  73.                                 if(rank == 0) rank = MAX_RANK;
  74.                                 y2 = (height-2*GRAPH_MARGIN_SIZE)* rank /MAX_RANK + GRAPH_MARGIN_SIZE;
  75.                                 GLine gl = new GLine(i*interval,y1,(i+1)*interval,y2);
  76.                                 GLabel label = new GLabel(itn.getName()+" "+new Integer(itn.getRank(i)).toString()
  77.                                                 ,i*interval,y1 );
  78.                                 gl.setColor(color);
  79.                                 label.setColor(color);
  80.                                 add(gl);
  81.                                 add(label);
  82.                         }
  83.                        
  84.                         /* Draw the last label*/
  85.                         GLabel label = new GLabel(itn.getName()+" "+new Integer(itn.getRank(NDECADES-1)).toString()
  86.                                         ,(NDECADES-1)*interval,y2);
  87.                         label.setColor(color);
  88.                         add(label);
  89.                 }
  90.                        
  91.         }
  92.        
  93.         private void drawBackground(int width,int height,int interval){
  94.                 /* Draw horizontal line */
  95.                 add(new GLine(0,GRAPH_MARGIN_SIZE,width,GRAPH_MARGIN_SIZE));
  96.                 add(new GLine(0,height-GRAPH_MARGIN_SIZE,width,height-GRAPH_MARGIN_SIZE));
  97.                 /* Draw vertical line */
  98.                 Integer decade = START_DECADE;
  99.                 add(new GLabel(decade.toString(),0,height));
  100.                 for(int i=1; i<NDECADES; i++){
  101.                         decade += 10;
  102.                         add(new GLine(i*interval,0,i*interval,height));
  103.                         add(new GLabel(decade.toString(),i*interval,height));
  104.                 }
  105.         }
  106.        
  107.         /* Get entry color */
  108.         private Color getColor(int entry){
  109.                 switch(entry%4){
  110.                 case 0: return Color.BLACK;
  111.                 case 1: return Color.RED;
  112.                 case 2: return Color.MAGENTA;
  113.                 case 3: return Color.BLUE;
  114.                 default: return Color.DARK_GRAY;
  115.                 }
  116.         }
  117.        
  118.         /* Implementation of the ComponentListener interface */
  119.         public void componentHidden(ComponentEvent e) { }
  120.         public void componentMoved(ComponentEvent e) { }
  121.         public void componentResized(ComponentEvent e) { update(); }
  122.         public void componentShown(ComponentEvent e) { }
  123.        
  124.         /* Variable */
  125.         private ArrayList<NameSurferEntry> entry_ar = new ArrayList<NameSurferEntry>();
  126. }
复制代码
回复

使用道具 举报

🔗
nprotect 2012-8-27 21:35:57 | 只看该作者
全局:
这次作业强调了top-down设计程序的思想,程序实现的东西不是太难,但是分了5个class,本次作业的难点,个人感觉在考察类之间调用方法的熟练程度,同时考察了字符串处理的操作。对于刚刚接触java以及面向对象程序设计的人来说,还是一次很不错的锻炼。

NameSurfer 类初始化了程序,添加component,设置actionPerformed

NameSurferDataBase 类实现了一行一行读入一个.txt文件的方法,并含有一个通过每行第一个name,返回整行的方法。

NameSurferEntry 类实现了把每行读入的string分解成一个string类型的name和11个int类型的排名,并储存在数组中。

NameSurferGraph 类实现了作图,画线,监听canvas变动。
回复

使用道具 举报

🔗
nprotect 2012-8-27 21:38:42 | 只看该作者
全局:
NameSurfer:
  1. /*
  2. * File: NameSurfer.java
  3. * ---------------------
  4. * When it is finished, this program will implements the viewer for
  5. * the baby-name database described in the assignment handout.
  6. */

  7. import acm.program.*;
  8. import java.awt.event.*;
  9. import javax.swing.*;

  10. @SuppressWarnings("serial")
  11. public class NameSurfer extends Program implements NameSurferConstants {

  12. /* Method: init() */
  13. /**
  14. * This method has the responsibility for reading in the data base
  15. * and initializing the interactors at the bottom of the window.
  16. */
  17.         public void init() {
  18.             name = new JLabel("Name");  
  19.             add(name, SOUTH);
  20.             textField = new JTextField(20);
  21.             add(textField, SOUTH);
  22.             graph = new JButton("Graph");
  23.             add(graph, SOUTH);
  24.             clear = new JButton("Clear");
  25.             add(clear, SOUTH);
  26.             
  27.             textField.addActionListener(this);
  28.             addActionListeners();
  29.             
  30.             picture = new NameSurferGraph();
  31.             add(picture);
  32.         }
  33.        
  34. /* Method: actionPerformed(e) */                                                               
  35. /**
  36. * This class is responsible for detecting when the buttons are
  37. * clicked, so you will have to define a method to respond to
  38. * button actions.
  39. */
  40.         public void actionPerformed(ActionEvent e) {   // actions
  41.                
  42.                 TRYONE = new NameSurferDataBase(NAMES_DATA_FILE);
  43.                 obj = TRYONE.findEntry(textField.getText());  // return an Object of NameSurferEntry
  44.                
  45.                 String cmd = e.getActionCommand();
  46.                 if (obj != null){
  47.                         if (cmd.equals("Graph"))            picture.addEntry(obj);            
  48.                         if (e.getSource() == textField)     picture.addEntry(obj);   
  49.                         if (cmd.equals("Clear"))            picture.clear();
  50.                 } else {
  51.                         System.out.println("No name!");    // 控制台弹出,有时间可以做成dialogue模式
  52.                 }
  53.         }

  54. /** instance variable*/
  55.         private JLabel name;
  56.         private JTextField textField;
  57.         private JButton graph;
  58.         private JButton clear;
  59.         private NameSurferGraph picture;
  60.         private NameSurferDataBase TRYONE;
  61.         private NameSurferEntry obj;


  62. }
复制代码
NameSurferDataBase:
  1. /*
  2. * File: NameSurferDataBase.java
  3. * -----------------------------
  4. * This class keeps track of the complete database of names.
  5. * The constructor reads in the database from a file, and
  6. * the only public method makes it possible to look up a
  7. * name and get back the corresponding NameSurferEntry.
  8. * Names are matched independent of case, so that "Eric"
  9. * and "ERIC" are the same names.
  10. */
  11. import java.io.*;
  12. import java.util.HashMap;

  13. public class NameSurferDataBase implements NameSurferConstants {
  14.        
  15. /* Constructor: NameSurferDataBase(filename) */
  16. /**
  17. * Creates a new NameSurferDataBase and initializes it using the
  18. * data in the specified file.  The constructor throws an error
  19. * exception if the requested file does not exist or if an error
  20. * occurs as the file is being read.
  21. */
  22.        
  23.         public NameSurferDataBase(String filename) {  // a class with a particular input parameter
  24.                 BufferedReader rd = null;
  25.                 try {
  26.                         rd = new BufferedReader(new FileReader(filename));
  27.                         while (true){
  28.                                 String line = rd.readLine();
  29.                                 if (line == null) break;   
  30.                                 /**这里,NameSurferEntry必须读入String类型的数据,所以要确保NameSurferEntry(line)
  31.                                  * 中的line有数据,所以if (line == null) break; 必须放在前面,否则当读取到最后一行
  32.                                  * 的时候,line == null了,NameSurferEntry就会报错
  33.                                  */
  34.                                 NameSurferEntry obj = new NameSurferEntry(line);  
  35.                                 data.put(obj.getName(), obj);  // corresponding name and NameSurferEntry
  36.                         }
  37.                         rd.close();
  38.                 }
  39.                 catch (IOException ex){
  40.                         System.out.println("no file!");
  41.                 }
  42.         }
  43.        
  44. /* Method: findEntry(name) */
  45. /**
  46. * Returns the NameSurferEntry associated with this name, if one
  47. * exists.  If the name does not appear in the database, this
  48. * method returns null.
  49. */
  50.         public NameSurferEntry findEntry(String name) {
  51.                 if (data.containsKey(name)) return data.get(name);
  52.                 return null;
  53.         }

  54. /** instance variable*/
  55.         private HashMap<String, NameSurferEntry> data = new HashMap<String, NameSurferEntry>();
  56.        
  57. }


复制代码
NameSurferEntry:
  1. /*
  2. * File: NameSurferEntry.java
  3. * --------------------------
  4. * This class represents a single entry in the database.  Each
  5. * NameSurferEntry contains a name and a list giving the popularity
  6. * of that name for each decade stretching back to 1900.
  7. */

  8. import java.util.*;

  9. public class NameSurferEntry implements NameSurferConstants {

  10. /* Constructor: NameSurferEntry(line) */
  11. /**
  12. * Creates a new NameSurferEntry from a data line as it appears
  13. * in the data file.  Each line begins with the name, which is
  14. * followed by integers giving the rank of that name for each
  15. * decade.
  16. */
  17.         public NameSurferEntry(String line) { // a class with particular input parameter
  18.                 StringTokenizer tokenizer = new StringTokenizer(line); // read from line and divide them into tokens
  19.                 name = tokenizer.nextToken();
  20.                 for (int i=0; i< NDECADES; i++){
  21.                         decadeArr[i]=Integer.parseInt(tokenizer.nextToken());
  22.                 }
  23.         }

  24. /* Method: getName() */
  25. /**
  26. * Returns the name associated with this entry.
  27. */
  28.         public String getName() {
  29.                 return name;
  30.         }

  31. /* Method: getRank(decade) */
  32. /**
  33. * Returns the rank associated with an entry for a particular
  34. * decade.  The decade value is an integer indicating how many
  35. * decades have passed since the first year in the database,
  36. * which is given by the constant START_DECADE.  If a name does
  37. * not appear in a decade, the rank value is 0.
  38. */
  39.         public int getRank(int decade) {  //decade: 0-10
  40.                 int rank = decadeArr[decade];
  41.                 return rank;
  42.         }

  43. /* Method: toString() */
  44. /**
  45. * Returns a string that makes it easy to see the value of a
  46. * NameSurferEntry.
  47. */
  48.         public String toString() {
  49.                 String returnValue = name + ": [";
  50.                 for (int i = 0; i< NDECADES; i++){
  51.                         returnValue = returnValue + decadeArr[i]+ " ";
  52.                 }
  53.                 returnValue = returnValue + "]";
  54.                 return returnValue;
  55.         }
  56.        
  57. /** instance variable*/
  58.         private int[] decadeArr = new int[NDECADES]; // 11-dimensional array
  59.         private String name;  // return name

  60. }



复制代码
NameSurferGraph:
  1. /*
  2. * File: NameSurferGraph.java
  3. * ---------------------------
  4. * This class represents the canvas on which the graph of
  5. * names is drawn. This class is responsible for updating
  6. * (redrawing) the graphs whenever the list of entries changes or the window is resized.
  7. */

  8. import acm.graphics.*;
  9. import java.awt.event.*;
  10. import java.util.*;
  11. import java.awt.*;

  12. public class NameSurferGraph extends GCanvas implements NameSurferConstants, ComponentListener {

  13.         /**
  14.         * Creates a new NameSurferGraph object that displays the data.
  15.         */
  16.         public NameSurferGraph() {
  17.                 addComponentListener(this);
  18.         }
  19.        
  20.         /**
  21.         * Clears the list of name surfer entries stored inside this class.
  22.         */
  23.         public void clear() {
  24.                 list.clear();
  25.                 update();
  26.         }
  27.        
  28.         /* Method: addEntry(entry) */
  29.         /**
  30.         * Adds a new NameSurferEntry to the list of entries on the display.
  31.         * Note that this method does not actually draw the graph, but
  32.         * simply stores the entry; the graph is drawn by calling update.
  33.         */
  34.         public void addEntry(NameSurferEntry entry) {
  35.                 list.add(entry);
  36.                 update();
  37.         }
  38.        
  39.         /**
  40.         * Updates the display image by deleting all the graphical objects
  41.         * from the canvas and then reassembling the display according to
  42.         * the list of entries. Your application must call update after
  43.         * calling either clear or addEntry; update is also called whenever
  44.         * the size of the canvas changes.
  45.         */
  46.         public void update() {
  47.                 /** re-sizable*/
  48.                 removeAll();
  49.                 GLine marginUp = new GLine (0, GRAPH_MARGIN_SIZE, getWidth(), GRAPH_MARGIN_SIZE);
  50.                 GLine marginDown = new GLine (0, getHeight()-GRAPH_MARGIN_SIZE, getWidth(), getHeight()-GRAPH_MARGIN_SIZE);
  51.                 add(marginUp);
  52.                 add(marginDown);
  53.                 for (int i=0; i<11; i++){
  54.                         GLine verticals = new GLine ((getWidth()/11)*i, 0,  (getWidth()/11)*i, getHeight());
  55.                         add(verticals);
  56.                 }
  57.                 for (int i=0; i<11; i++){
  58.                         int temp = 1900+10*i;
  59.                         String s= String.valueOf(temp);
  60.                         GLabel years = new GLabel(s, (getWidth()/11)*i, getHeight());
  61.                         add(years);
  62.                 }
  63.                 /** graphic operation*/
  64.                 int k = getHeight()-GRAPH_MARGIN_SIZE*2;  // height for calculate
  65.                 int n = list.size();   // if there exist 4 elements, the index of them is:0,1,2,3
  66.                 while ((n-1) >=0){
  67.                         NameSurferEntry obj = list.get(n-1);         // list.get(n-1) is the object of NameSurferEntry
  68.                                 for (int i=0; i<10; i++){                // draw line
  69.                                         rankOfName = obj.getRank(i);      
  70.                                         rankOfNextName = obj.getRank(i+1);     
  71.                                         if (rankOfName == 0) rankOfName = 1001;           // lower the 0 coordinate
  72.                                         if (rankOfNextName == 0) rankOfNextName = 1001;   // lower the 0 coordinate
  73.                                         GLine x = new GLine(getWidth()*i/11, rankOfName*k/MAX_RANK+20, getWidth()*(i+1)/11, rankOfNextName*k/MAX_RANK+20);
  74.                                         x.setColor(myColor(n-1));
  75.                                         add(x);   //  take care of the accuracy in JAVA!! Some times division get an “0” !!
  76.                                         intToString = String.valueOf(rankOfName);  
  77.                                         if (rankOfName == 1001) intToString = "*";
  78.                                         GLabel y = new GLabel(obj.getName()+" "+intToString, getWidth()*i/11, rankOfName*k/MAX_RANK+20);
  79.                                         y.setColor(myColor(n-1));
  80.                                         add(y);
  81.                                 }
  82.                                 /** the last label of name*/
  83.                                 String intToStringNext = String.valueOf(rankOfNextName);
  84.                                 if (rankOfNextName == 1001) intToStringNext = "*";
  85.                                 GLabel z = new GLabel(obj.getName()+" "+ intToStringNext, getWidth()/11*10, rankOfNextName*k/MAX_RANK+20);
  86.                                 z.setColor(myColor(n-1));
  87.                                 add(z);
  88.                                 n--;
  89.                 }
  90.         }
  91.        
  92.         private Color myColor(int num){
  93.                 switch (num%4){
  94.                 case 0: return Color.black;
  95.                 case 1: return Color.red;
  96.                 case 2: return Color.blue;
  97.                 case 3: return Color.magenta;
  98.                 default: return Color.black;
  99.                 }
  100.         }
  101.        
  102.         /* Implementation of the ComponentListener interface */
  103.         public void componentHidden(ComponentEvent e) { }
  104.         public void componentMoved(ComponentEvent e) { }
  105.         public void componentResized(ComponentEvent e) { update(); }
  106.         public void componentShown(ComponentEvent e) { }
  107.        
  108. /**instance variable*/
  109.         private ArrayList <NameSurferEntry> list = new ArrayList <NameSurferEntry>();
  110.         private int rankOfName;      // rank of the name, the value of "i" in obj.getRank(i) is 9 when circle ends
  111.         private int rankOfNextName;  // rank of the next name, the value of "i" in obj.getRank(i) is 10 when circle ends
  112.         private String intToString;  // convert rankOfName from integer to string type
  113. }
复制代码
NameSurferConstants:
  1. /*
  2. * File: NameSurferConstants.java
  3. * ------------------------------
  4. * This file declares several constants that are shared by the
  5. * different modules in the NameSurfer application.  Any class
  6. * that implements this interface can use these constants.
  7. */

  8. public interface NameSurferConstants {

  9. /** The width of the application window */
  10.         public static final int APPLICATION_WIDTH = 800;

  11. /** The height of the application window */
  12.         public static final int APPLICATION_HEIGHT = 600;

  13. /** The name of the file containing the data */
  14.         public static final String NAMES_DATA_FILE = "names-data.txt";

  15. /** The first decade in the database */
  16.         public static final int START_DECADE = 1900;

  17. /** The number of decades */
  18.         public static final int NDECADES = 11;

  19. /** The maximum rank in the database */
  20.         public static final int MAX_RANK = 1000;

  21. /** The number of pixels to reserve at the top and bottom */
  22.         public static final int GRAPH_MARGIN_SIZE = 20;

  23. }
复制代码


回复

使用道具 举报

🔗
nprotect 2012-8-27 21:44:10 | 只看该作者
全局:
还有最后一个assigment,赶快做完我也要走了。
回复

使用道具 举报

无效楼层,该帖已经被删除
全局:
前两天毫无干劲……本来以为今天晚上完不成,没想到还是完成了。这次不难,但是大量的时间都花在脑残的笔误上
  1. /*
  2. * File: NameSurfer.java
  3. * ---------------------
  4. * When it is finished, this program will implements the viewer for
  5. * the baby-name database described in the assignment handout.
  6. */

  7. import acm.program.*;
  8. import java.awt.event.*;
  9. import javax.swing.*;
  10. import java.awt.*;
  11. import java.util.ArrayList;

  12. public class NameSurfer extends Program implements NameSurferConstants {

  13. /* Method: init() */
  14. /**
  15. * This method has the responsibility for reading in the data base
  16. * and initializing the interactors at the bottom of the window.
  17. */
  18.         public void init() {
  19.             // You fill this in, along with any helper methods //
  20.                 graph=new NameSurferGraph();
  21.                 add(graph);
  22.                 data=new NameSurferDataBase("names-data.txt");
  23.                 setLayout(new GridLayout(1,1));
  24.                 Graph=new JButton("Graph");
  25.                 Clear=new JButton("Clear");
  26.                 tf=new JTextField(10);
  27.                 tf.addActionListener(this);
  28.                 add(new JLabel("Name"),SOUTH);
  29.                 add(tf,SOUTH);
  30.                 add(Graph,SOUTH);
  31.                 add(Clear,SOUTH);
  32.                 addActionListeners();
  33.                
  34.                
  35.         }

  36. /* Method: actionPerformed(e) */
  37. /**
  38. * This class is responsible for detecting when the buttons are
  39. * clicked, so you will have to define a method to respond to
  40. * button actions.
  41. */
  42.         public void actionPerformed(ActionEvent e) {
  43.                 // You fill this in //
  44.                 String cmd=e.getActionCommand();
  45.                
  46.                 if(cmd.equals("Graph")){
  47.                         graph.update();
  48.                         graph.addEntry(data.findEntry(tf.getText()));
  49.                        
  50.                         graph.addLine();
  51.                        
  52.                        
  53.                        
  54.                                 //println("Graph: "+data.findEntry(tf.getText()).toString());
  55.                        

  56.                 }
  57.                 if(cmd.equals("Clear")){
  58.                         graph.update();
  59.                         graph.setNull();
  60.                         //println("Clear");
  61.                 }
  62.                        
  63.                
  64.         }
  65.        
  66.         //private NameSurferGraph[] graphs=new NameSurferGraph[5];
  67.         //private ArrayList<NameSurferGraph> graphs=new ArrayList<NameSurferGraph>();
  68.         private NameSurferGraph graph;
  69.         private NameSurferDataBase data;
  70.         private JTextField tf;
  71.         private JButton Graph;
  72.         private JButton Clear;

  73. }
  74.        
复制代码
  1. /*
  2. * File: NameSurferGraph.java
  3. * ---------------------------
  4. * This class represents the canvas on which the graph of
  5. * names is drawn. This class is responsible for updating
  6. * (redrawing) the graphs whenever the list of entries changes or the window is resized.
  7. */

  8. import acm.graphics.*;
  9. import java.awt.event.*;
  10. import java.util.*;
  11. import java.awt.*;

  12. public class NameSurferGraph extends GCanvas
  13.         implements NameSurferConstants, ComponentListener {

  14.         /**
  15.         * Creates a new NameSurferGraph object that displays the data.
  16.         */
  17.         public NameSurferGraph() {
  18.                
  19.                 addComponentListener(this);
  20.                 temp = 0;
  21.                
  22.                
  23.                
  24.                
  25.                
  26.                
  27.                 //         You fill in the rest //
  28.         }
  29.         public String year(int i){
  30.                 if (i==0) return "1900";
  31.                 else if(i==1) return "1910";
  32.                 else if(i==2) return "1920";
  33.                 else if(i==3) return "1930";
  34.                 else if(i==4) return "1940";
  35.                 else if(i==5) return "1950";
  36.                 else if(i==6) return "1960";
  37.                 else if(i==7) return "1970";
  38.                 else if(i==8) return "1980";
  39.                 else if(i==9) return "1990";
  40.                 else return "2000";
  41.         }
  42.                
  43.         /**
  44.         * Clears the list of name surfer entries stored inside this class.
  45.         */
  46.         public void clear() {
  47.                 //         You fill this in //
  48.         }
  49.        
  50.         /* Method: addEntry(entry) */
  51.         /**
  52.         * Adds a new NameSurferEntry to the list of entries on the display.
  53.         * Note that this method does not actually draw the graph, but
  54.         * simply stores the entry; the graph is drawn by calling update.
  55.         */
  56.         public void addEntry(NameSurferEntry entry) {
  57.                 if(temp<5){
  58.                         entries[temp]=entry;
  59.                         temp++;
  60.                         }
  61.                 else{
  62.                         entries[0]=entry;
  63.                         temp=0;
  64.                 }
  65.                
  66.                 // You fill this in //
  67.                
  68.                
  69.                
  70.         }
  71.        
  72.        
  73.        
  74.         /**
  75.         * Updates the display image by deleting all the graphical objects
  76.         * from the canvas and then reassembling the display according to
  77.         * the list of entries. Your application must call update after
  78.         * calling either clear or addEntry; update is also called whenever
  79.         * the size of the canvas changes.
  80.         */
  81.         public void update() {
  82.                 removeAll();
  83.                 add(new GLine(0,GRAPH_MARGIN_SIZE,getWidth(),GRAPH_MARGIN_SIZE));
  84.                 add(new GLine(0,getHeight()-GRAPH_MARGIN_SIZE,getWidth(),getHeight()-GRAPH_MARGIN_SIZE));
  85.                 for(int h=0;h<NDECADES;h++){
  86.                         add(new GLine(getWidth()/NDECADES*(h),0,getWidth()/NDECADES*(h),getHeight()));
  87.                         add(new GLabel(year(h),getWidth()/NDECADES*(h),getHeight()));
  88.                 }
  89.                 //         You fill this in //
  90.                
  91.        
  92.         }
  93.         public void addLine(){
  94.                 /*
  95.                 GLine line=new GLine(0,GRAPH_MARGIN_SIZE+entries[0].getRank(1900)*(getHeight()-2*GRAPH_MARGIN_SIZE)/1000,
  96.                                 getWidth(),GRAPH_MARGIN_SIZE+entries[0].getRank(1910)*(getHeight()-2*GRAPH_MARGIN_SIZE)/1000);
  97.                 add(line);
  98.                 line.setColor(Color.RED);
  99.                 */
  100.        

  101.                 for(int i=0;i<5;i++){
  102.                         for(int j=0;j<11;j++){
  103.                                
  104.                                 if(entries[i]!=null){
  105.                                         int y1=GRAPH_MARGIN_SIZE+entries[i].getRank(1900+j*10)*(getHeight()-2*GRAPH_MARGIN_SIZE)/1000;
  106.                                         int y2=GRAPH_MARGIN_SIZE+entries[i].getRank(1900+(j+1)*10)*(getHeight()-2*GRAPH_MARGIN_SIZE)/1000;
  107.                                         if(y1==GRAPH_MARGIN_SIZE)y1=getHeight()-GRAPH_MARGIN_SIZE;
  108.                                         if(y2==GRAPH_MARGIN_SIZE)y2=getHeight()-GRAPH_MARGIN_SIZE;
  109.                                         if(j!=10){
  110.                                        
  111.                                        
  112.                                         GLine line=new GLine(j*getWidth()/NDECADES,y1,(j+1)*getWidth()/NDECADES,y2);
  113.                                         add(line);
  114.                                         if(i==1) line.setColor(Color.RED);
  115.                                         if(i==2) line.setColor(Color.ORANGE);
  116.                                         if(i==3) line.setColor(Color.BLUE);
  117.                                         if(i==4) line.setColor(Color.GREEN);
  118.                                         }
  119.                                                                                
  120.                                         String rank=Integer.toString(entries[i].getRank(1900+j*10));
  121.                                         if(rank.equals("0")) rank="*";
  122.                                         GLabel label=new GLabel(entries[i].getName()+" "+rank,j*getWidth()/NDECADES+1,y1+1);
  123.                                         add(label);
  124.                                         if(i==1) label.setColor(Color.RED);
  125.                                         if(i==2) label.setColor(Color.ORANGE);
  126.                                         if(i==3) label.setColor(Color.BLUE);
  127.                                         if(i==4) label.setColor(Color.GREEN);
  128.                                        
  129.                                        
  130.                                 }
  131.                        
  132.                 }
  133.                 }

  134.         }
  135.        
  136.        
  137.        
  138.         public void setNull(){
  139.                 for(int i=0;i<5;i++){
  140.                         entries[i]=null;
  141.                 }
  142.         }
  143.        
  144.         /* Implementation of the ComponentListener interface */
  145.         public void componentHidden(ComponentEvent e) { }
  146.         public void componentMoved(ComponentEvent e) { }
  147.         public void componentResized(ComponentEvent e) { update(); }
  148.         public void componentShown(ComponentEvent e) { }
  149.        
  150.         private int temp;
  151.         //private ArrayList<NameSurferEntry> entries=new ArrayList<NameSurferEntry>();
  152.         NameSurferEntry[] entries=new NameSurferEntry[5];
  153.        
  154. }
复制代码
  1. /*
  2. * File: NameSurferEntry.java
  3. * --------------------------
  4. * This class represents a single entry in the database.  Each
  5. * NameSurferEntry contains a name and a list giving the popularity
  6. * of that name for each decade stretching back to 1900.
  7. */

  8. import acm.util.*;
  9. import java.util.*;

  10. public class NameSurferEntry implements NameSurferConstants {

  11. /* Constructor: NameSurferEntry(line) */
  12. /**
  13. * Creates a new NameSurferEntry from a data line as it appears
  14. * in the data file.  Each line begins with the name, which is
  15. * followed by integers giving the rank of that name for each
  16. * decade.
  17. */
  18.         public NameSurferEntry(String line) {
  19.                
  20.                
  21.                 // You fill this in //
  22.                 int nameEnd=line.indexOf(" ");
  23.                 name=line.substring(0,nameEnd);
  24.                 int first=line.indexOf(" ",nameEnd)+1;
  25.                 int second=line.indexOf(" ",first)+1;
  26.                 int third=line.indexOf(" ",second)+1;
  27.                 int forth=line.indexOf(" ",third)+1;
  28.                 int fifth=line.indexOf(" ",forth)+1;
  29.                 int sixth=line.indexOf(" ",fifth)+1;
  30.                 int seventh=line.indexOf(" ",sixth)+1;
  31.                 int eighth=line.indexOf(" ",seventh)+1;
  32.                 int ninth=line.indexOf(" ",eighth)+1;
  33.                 int tenth=line.indexOf(" ",ninth)+1;
  34.                 int eleventh=line.indexOf(" ",tenth)+1;
  35.                
  36.                 /*
  37.                 one=line.substring(first,second-1);
  38.                 two=line.substring(second,third-1);
  39.                 three=line.substring(third,forth-1);
  40.                 four=line.substring(forth,fifth-1);
  41.                 five=line.substring(fifth,sixth-1);
  42.                 six=line.substring(sixth,seventh-1);
  43.                 seven=line.substring(seventh,eighth-1);
  44.                 eight=line.substring(eighth,ninth-1);
  45.                 nine=line.substring(ninth,tenth-1);
  46.                 ten=line.substring(tenth,eleventh-1);
  47.                 eleven=line.substring(eleventh+1);
  48.                 */
  49.                
  50.                 one=Integer.parseInt(line.substring(first,second-1));
  51.                 two=Integer.parseInt(line.substring(second,third-1));
  52.                 three=Integer.parseInt(line.substring(third,forth-1));
  53.                 four=Integer.parseInt(line.substring(forth,fifth-1));
  54.                 five=Integer.parseInt(line.substring(fifth,sixth-1));
  55.                 six=Integer.parseInt(line.substring(sixth,seventh-1));
  56.                 seven=Integer.parseInt(line.substring(seventh,eighth-1));
  57.                 eight=Integer.parseInt(line.substring(eighth,ninth-1));
  58.                 nine=Integer.parseInt(line.substring(ninth,tenth-1));
  59.                 ten=Integer.parseInt(line.substring(tenth,eleventh-1));
  60.                 eleven=Integer.parseInt(line.substring(eleventh));
  61.                 //eleven=line.substring(eleventh);
  62.                
  63.                
  64.         }

  65. /* Method: getName() */
  66. /**
  67. * Returns the name associated with this entry.
  68. */
  69.         public String getName() {
  70.                 // You need to turn this stub into a real implementation //
  71.                 return name;
  72.                 //return null;
  73.         }

  74. /* Method: getRank(decade) */
  75. /**
  76. * Returns the rank associated with an entry for a particular
  77. * decade.  The decade value is an integer indicating how many
  78. * decades have passed since the first year in the database,
  79. * which is given by the constant START_DECADE.  If a name does
  80. * not appear in a decade, the rank value is 0.
  81. */
  82.         public int getRank(int decade) {
  83.                 // You need to turn this stub into a real implementation //
  84.                 if(decade==1900) return one;
  85.                 else if(decade==1910) return two;
  86.                 else if(decade==1920) return three;
  87.                 else if(decade==1930) return four;
  88.                 else if(decade==1940) return five;
  89.                 else if(decade==1950) return six;
  90.                 else if(decade==1960) return seven;
  91.                 else if(decade==1970) return eight;
  92.                 else if(decade==1980) return nine;
  93.                 else if(decade==1990) return ten;
  94.                 else return eleven;
  95.                
  96.         }

  97. /* Method: toString() */
  98. /**
  99. * Returns a string that makes it easy to see the value of a
  100. * NameSurferEntry.
  101. */
  102.         public String toString() {
  103.                 // You need to turn this stub into a real implementation //
  104.                 //return (name+" ["+one+" "+two+" "+three+" "+four+" "+five+" "+six+" "+seven+" "+eight+" "+nine+" "+ten+" ]");
  105.                 return (name+" ["+one+" "+two+" "+three+" "+four+" "+five+" "+six+" "+seven+" "+eight+" "+nine+" "+ten+" "+eleven+"]");
  106.         }
  107.        
  108.         private int one, two, three, four, five, six, seven, eight, nine, ten, eleven;
  109.         //private int one, two, three, four, five, six, seven, eight, nine, ten, eleven;

  110.         private String name;
  111. }
复制代码
  1. /*
  2. * File: NameSurferDataBase.java
  3. * -----------------------------
  4. * This class keeps track of the complete database of names.
  5. * The constructor reads in the database from a file, and
  6. * the only public method makes it possible to look up a
  7. * name and get back the corresponding NameSurferEntry.
  8. * Names are matched independent of case, so that "Eric"
  9. * and "ERIC" are the same names.
  10. */
  11. import acm.util.*;
  12. import acm.program.*;
  13. import java.io.*;
  14. import java.util.*;
  15. import java.awt.*;

  16. public class NameSurferDataBase implements NameSurferConstants  {
  17.        
  18. /* Constructor: NameSurferDataBase(filename) */
  19. /**
  20. * Creates a new NameSurferDataBase and initializes it using the
  21. * data in the specified file.  The constructor throws an error
  22. * exception if the requested file does not exist or if an error
  23. * occurs as the file is being read.
  24. */
  25.         public NameSurferDataBase(String filename) {
  26.                 // You fill this in //
  27.                 try{
  28.                         BufferedReader rd=new BufferedReader(new FileReader(filename));
  29.                         while(true){
  30.                                 String line=rd.readLine();
  31.                                 if(line==null)break;
  32.                                 entry=new NameSurferEntry(line);
  33.                                 entries.add(entry);
  34.                                        
  35.                         }
  36.                         rd.close();
  37.                 } catch (IOException ex){
  38.                          throw new ErrorException(ex);
  39.                 }
  40.                                        
  41.         }
  42.        
  43. /* Method: findEntry(name) */
  44. /**
  45. * Returns the NameSurferEntry associated with this name, if one
  46. * exists.  If the name does not appear in the database, this
  47. * method returns null.
  48. */
  49.         public NameSurferEntry findEntry(String name) {
  50.                 // You need to turn this stub into a real implementation //
  51.                 int temp=-1;
  52.                 for(int i=0;i<entries.size();i++){
  53.                         if(name.equals(entries.get(i).getName())){
  54.                                 temp=i;
  55.                                
  56.                         }
  57.                 }
  58.                
  59.                 if(temp==-1)return(null);
  60.                 else {
  61.                         return(entries.get(temp));
  62.                 }
  63.         }
  64.         private ArrayList<NameSurferEntry> entries=new ArrayList<NameSurferEntry>();
  65.         private NameSurferEntry entry;
  66.         private String nameref;
  67.         private String Name;
  68. }
复制代码
回复

使用道具 举报

🔗
jby1797 2014-1-20 10:38:11 | 只看该作者
全局:
感觉这个作业难度虽然不大,但是老师给的handout里提示越来越少,越来越多靠自己了。
这次作业不难,但是很多小细节需要注意,debug花的时间越来越多。
以data structure为主了好像,我不太懂,反正就是稀里糊涂又做出来了。

从第一个作业做到倒数第二个,感觉就是回复的人越来越少。
这确实是一门很好的课,大家加油!

回复

使用道具 举报

🔗
jby1797 2014-1-20 10:39:38 | 只看该作者
全局:
忘记上图了。。。不能编辑


可大可小,线的颜色不一样

点评

老古董的XP系统是不是特别个性。。。  发表于 2014-1-20 10:40

评分

参与人数 1学分 +1 收起 理由
sanguine + 1 好高端的样子--

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表