[Java]基本的學習執行個體

來源:互聯網
上載者:User
好久沒有更新了,偷懶,該打!
1、這個是一個基本的檔案操作,實現對檔案讀取、寫入一個數位操作的
package trying;
import java.io.*;

/**
* @author gooing
*/
public class FileRw {
private File f = new File("d:\\j2\\a.txt");
public int getNum(){
int i = -1;
try{
String stri="";
BufferedReader in = new BufferedReader(new FileReader(f));
while((stri=in.readLine())!=null){
i = Integer.parseInt(stri.trim());
}
in.close();
}catch(Exception e){
e.printStackTrace();
}
return i;
}
public void setNum(){
int i = getNum();
i++;
try{
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f,false)));
out.write(String.valueOf(i));
//可能是編碼的原因,如果直接寫入int的話,將出現java編碼和windows編碼的混亂,因此此處寫入的是String
out.close() ;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
FileRw frw = new FileRw();
for(int i =0;i<100; i++){
frw.setNum();
System.out.println(frw.getNum());
}
}
}

2、下面這個是學習原廠模式的一個例子
//Garden.java實現一個抽象花園工廠,你可以從中得到該花園的中心植物和周邊植物;
//當然,對於不同的花園而言,其中心植物和周邊植物是不一樣的
package pkgfactory;

/**
* @author gooing TODO To change the template for this generated type
* comment go to Window - Preferences - Java - Code Style - Code
* Templates
*/
public abstract class Garden {
public abstract Plant getCenter();
public abstract Plant getBorder();

public void memo() {
System.out.println("CenterPlant:" + getCenter().getName());
System.out.println("BorderPlant:" + getBorder().getName());
System.out.println("---------------------");
}
}

//Plant.java 實現對花園中植物的基本抽象,此處只提供一個植物的name屬性
package pkgfactory;
public class Plant {
public Plant(String name) {
this.name = name;
}

public String getName() {
return name;
}

private String name;
}

//VerGarden.java 和FlowerGarden.java 分別實現了一個菜園子和花園子
package pkgfactory;
public class VegGarden extends Garden {
public Plant getCenter() {
return new Plant("Wheat");
}

public Plant getBorder() {
return new Plant("Carrot");
}
}

package pkgfactory;
public class FlowerGarden extends Garden {
public Plant getCenter() {
return new Plant("Rose");
}

public Plant getBorder() {
return new Plant("JuHua");
}
}

//Gardener.java是該常式的一個驅動
package pkgfactory;
public class Gardener {
public static void main(String[] args) {
Garden g1 = new FlowerGarden();
Garden g2 = new VegGarden();
g1.memo();
g2.memo();
}
}






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.