2016/5/21学习记录

1.重大教训!先上代码

 1 package Pra;
 2 
 3 public class Read {
 4     
 5     public static void main(String[] args) {
 6     T a = new T();
 7     Read.swap(a);
 8     System.out.println("e1 = "+a.e1+"e2 = "+a.e2);
 9     }
10     public static void swap(T t){
11     int temp = t.e1;
12     t.e1 = t.e2;
13     t.e2 = temp;
14     
15 }
16 }
17  class T {
18      T(){}
19      int e1 = 1;
20      int e2 = 2;
21 }

这段代码之前一直出错“No enclosing instance of type  is accessible. ”百度了一下,如下,跟我的情况一样,把下面的类class改成static确实解决了问题。

但总觉得哪里不对,因为理论上静态方法不能调用实例方法或者访问实例数据域,因为静态方法和静态数据域不属于某个特定的对象,但是实例化之后就可以了啊。

后来我发现我的括号打错了!!!!结果就是Class T写在了Class Read里面,实际上在mian函数里面实例化了T,也可以进行引用的。

所以不能轻信楼上这种做法!吸取点教训。

2.P305 exercise9.1

 1 package Exercise;
 2 
 3 public class Rectangle {
 4     private double width = 1;
 5     private double height = 1;
 6     Rectangle(){
 7     }
 8     Rectangle(double width,double height){
 9         this.width = width;
10         this.height = height;
11     }
12     public double getArea(){
13         return width*height;
14     }
15     public double getPerimeter(){
16         return 2*(width+height);
17     }
18     public void print(){
19         System.out.println("The width of the rectangle is "+width);
20         System.out.println("The height of the rectangle is "+height);
21         System.out.println("The Area of the rectangle is "+getArea());
22         System.out.println("The Perimeter of the rectangle is "+getPerimeter());
23     }
24     public static void main(String[] args) {
25      Rectangle t1 = new Rectangle(4,40);
26     t1.print();
27     }
28 
29 }

3.Exercise 9.2

 1 package Exercise;
 2 
 3 
 4 public class Stock {
 5     private String symbol ;
 6     private String name;
 7     private double PCR;
 8     private double CP;
 9     Stock(String symbol,String name){
10         this.symbol = symbol;
11         this.name = name;
12     }
13     double getChangePercent(){
14         return ((CP-PCR)/PCR*100);
15     }
16     void print(){
17         System.out.println("the symbol of the stock is "+symbol);
18         System.out.println("the name of the stock is "+name);
19         System.out.printf("%4.2f",Math.abs(getChangePercent()));
20     }
21     public static void main(String[] args) {
22     Stock s = new Stock("Orcl","Oracle Corp");
23     s.PCR = 34.5;
24     s.CP = 34.35;
25     s.print();
26     }
27 
28 }

 

posted @ 2016-05-21 22:02  来搞笑的  阅读(131)  评论(0编辑  收藏  举报