1.abstracttest
package abstracttest;
/*
* 抽象類和抽象方法
* 抽象類也可以像普通類一樣,有構造方法、一般方法、屬性,
* 更重要的是還可以有一些抽象方法,留給子類去實現,而且在抽象類中聲明構造方法後,在子類中必須明確調用。
*/
abstract public class Abstract {
String name ;
int age ;
String occupation ;
public Abstract(String name){
this.name=name;
}
public Abstract(String name,int age,String occupation)
{
this.name = name ;
this.age = age ;
this.occupation = occupation ;
}
// 聲明一抽象方法talk()
public abstract String talk() ;
}
package abstracttest;
public class ExtendAbstract extends Abstract {
public ExtendAbstract(String name) {
super(name);
}
//與一般類相同,在抽象類中,也可以擁有構造方法,但是這些構造方法必須在子類中被調用。
// public ExtendAbstract(String name,int age,String occupation)
// {
// this.name = name ;
// this.age = age ;
// this.occupation = occupation ;
// }
public ExtendAbstract(String name, int age, String occupation) {
super(name, age, occupation);
}
public String talk() {
return "學生——>姓名:"+this.name+",年齡:"+this.age+",職業: 22 "+this.occupation+"!" ;
}
}
package abstracttest;
public class AbstarctTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExtendAbstract extendabstract=new ExtendAbstract("張三",20,"學生");
System.out.println(extendabstract.talk());
}
}
2.array
package array;
public class ArrayCopy {
/**
* @數組的拷貝
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a1[] = {1,2,3,4,5} ; //聲明兩個整型數組a1、a2,並進行靜態初始化
int a2[] = {9,8,7,6,5,4,3} ;
System.arraycopy(a1,0,a2,0,3); // 執行數組拷貝的操作,System.arrayCopy(source,0,dest,0,x):
//語句的意思就是:複製源數組從下標0開始的x個元素到目標數組,
//從目標數組的下標0所對應的位置開始存取。
System.out.print("a1數組中的內容:");
for(int i=0;i<a1.length;i++) // 輸出a1數組中的內容
System.out.print(a1[i]+" ");
System.out.print("\na2數組中的內容:");
for(int i=0;i<a2.length;i++) //輸出a2數組中的內容
System.out.print(a2[i] +" ");
System.out.println("\n數組拷貝完成!");
}
}
package array;
import java.util.Arrays;
public class ArraySort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {4,32,45,32,65,32,2} ;
System.out.print("數組排序前的順序:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
Arrays.sort(a); // 數組的排序方法
System.out.print("\n數組排序後的順序:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
package array;
public class ArrayTest {
/**
* @數組
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,min,max;
int A[]={74,48,30,17,62}; // 聲明整數數組A,並賦初值
min=max=A[0];
System.out.print("數組A的元素包括: ");
for(i=0;i<A.length;i++)
{
System.out.print(A[i]+" ");
if(A[i]>max) // 判斷最大值
max=A[i];
if(A[i]<min) // 判斷最小值
min=A[i];
}
System.out.println("\n數組的最大值是:"+max); // 輸出最大值
System.out.println("數組的最小值是:"+min); //
}
}
package array;
public class TwoArrayTest {
private static int ss;
static int ii;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,sum=0;
int num[][]={{30,35,26,32},{33,34,30,29},{22,34,24,56}}; // 聲明數組並設置初值
for(i=0;i<num.length;i++) // 輸出銷售量並計算總銷售量
{
System.out.print("第 "+(i+1)+" 個人的成績爲:");
System.out.println(i);
for(j=0;j<num[i].length;j++)
{
System.out.print(num[i][j]+" ");
sum+=num[i][j];
}
System.out.println();
}
System.out.println("總成績是 "+sum+" 分!");
}
}
3.collection
package collection;
import java.awt.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
public class CollectionDemo {
/**
* Collection操作
*/
public static void main(String[] args) {
//Collection collectionss=(Collection) new List();
//Object[] a=(Object[]) new Object();
Collection collection1=new ArrayList();
//Collection collection1=new LinkedList(); //創建一個集合對象
System.out.println(collection1.add("333"));
collection1.add("000"); //添加對象到Collection 集合中
collection1.add("111");
collection1.add("222");
System.out.println("集合collection1 的大小:"+collection1.size());
System.out.println("集合collection1 的內容:"+collection1);
collection1.remove("000"); //從集合collection1 中移除掉 "000" 這個對象
System.out.println("集合collection1 移除 000 後的內容:"+collection1);
System.out.println("集合collection1 中是否包含000 :"+collection1.contains("000"));
System.out.println("集合collection1 中是否包含111 :"+collection1.contains("111"));
Collection collection2=new ArrayList();
collection2.addAll(collection1); //將collection1 集合中的元素全部都加到collection2中
System.out.println("集合collection2 的內容:"+collection2);
collection2.clear(); //清空集合 collection1 中的元素
System.out.println("集合collection2 是否爲空:"+collection2.isEmpty());
//將集合collection1 轉化爲數組
Object s[]= collection1.toArray();
//Object s[]= collection1.toArray(Object[] a);
for(int i=0;i<s.length;i++){
System.out.println(s[i]);
}
}
}
package collection;
import java.util.*;
public class IteratorDemo {
/**
* 迭代器
*/
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add("s1");
collection.add("s2");
collection.add("s3");
Iterator iterator = collection.iterator();//得到一個迭代器
while (iterator.hasNext()) {//遍歷
Object element = iterator.next();
System.out.println("iterator = " + element);
}
if(collection.isEmpty())
System.out.println("collection is Empty!");
else
System.out.println("collection is not Empty! size="+collection.size());
Iterator iterator2 = collection.iterator();
while (iterator2.hasNext()) {//移除元素
Object element = iterator2.next();
System.out.println("remove: "+element);
iterator2.remove();
}
Iterator iterator3 = collection.iterator();
if (!iterator3.hasNext()) {//察看是否還有元素
System.out.println("還有元素:"+iterator.hasNext());
}
if(collection.isEmpty())
System.out.println("collection is Empty!");
//使用collection.isEmpty()方法來判斷
System.out.println(collection.size());
}
}
package collection;
import java.util.LinkedList;
public class LinkedListDemo {
/**
* LinkedList
*/
public static void main(String[] args) {
LinkedList linkedlist=new LinkedList();
linkedlist.addFirst("Bernadine");
linkedlist.addFirst("Elizabeth");
linkedlist.addFirst("Gene");
linkedlist.addFirst("Elizabeth");
linkedlist.addFirst("Clara");
System.out.println(linkedlist.get(3));
System.out.println(linkedlist);
linkedlist.removeLast();
linkedlist.removeLast();
System.out.println(linkedlist);
}
}
package collection;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorDemo {
/**
* ListIteratorDemo
*/
public static void main(String[] args) {
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
System.out.println("下標0 開始:"+list.listIterator(0).next()); //next()
System.out.println("下標1 開始:"+list.listIterator(1).next());
System.out.println("子List 1-3:"+list.subList(1,3)); //子列表
ListIterator it = list.listIterator(); //默認從下標0 開始
//隱式光標屬性add 操作 ,插入到當前的下標的前面
it.add("sss");
System.out.println(it.next());
System.out.println(it.nextIndex());
System.out.println(it.next());
while(it.hasNext()){
System.out.println("Index="+it.nextIndex()+",Object="+it.next());
}
ListIterator it1 = list.listIterator();
System.out.println(it1.next());
it1.set("ooo");
ListIterator it2 = list.listIterator(list.size());//下標
while(it2.hasPrevious()){
System.out.println("previous Index="+it2.previousIndex()+",Object="+it2.previous());
}
}
}
package collection;
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
/**
*Map
*/
public static void main(String[] args) {
Map map1 = new HashMap();
Map map2 = new HashMap();
map1.put("1","aaa1");
map1.put("2","bbb2");
map2.put("10","aaaa10");
map2.put("11","bbbb11");
//根據鍵 "1" 取得值:"aaa1"
System.out.println("map1.get(\"1\")="+map1.get("1"));
// 根據鍵 "1" 移除鍵值對"1"-"aaa1"
System.out.println("map1.remove(\"1\")="+map1.remove("1"));
System.out.println("map1.get(\"1\")="+map1.get("1"));
map1.putAll(map2);//將map2 全部元素放入map1 中
map2.clear();//清空map2
System.out.println("map1 IsEmpty?="+map1.isEmpty());
System.out.println("map2 IsEmpty?="+map2.isEmpty());
System.out.println("map1 中的鍵值對的個數size = "+map1.size());
System.out.println("KeySet="+map1.keySet());//set
System.out.println("values="+map1.values());//Collection
System.out.println("entrySet="+map1.entrySet());
System.out.println("map1 是否包含鍵:11 = "+map1.containsKey("11"));
System.out.println("map1 是否包含值:aaa1 = "+map1.containsValue("aaa1"));
}
}
package collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetDemo {
/**
* @param args
*/
public static void main(String[] args) {
Set set1 = new HashSet();
if (set1.add("a")) {//添加成功
System.out.println("1 add true");
}
if (set1.add("a")) {//添加失敗
System.out.println("2 add true");
}
set1.add("000");//添加對象到Set 集合中
set1.add("111");
set1.add("222");
System.out.println("集合set1 的大小:"+set1.size());
System.out.println("集合set1 的內容:"+set1);
set1.remove("000");//從集合set1 中移除掉 "000" 這個對象
System.out.println("集合set1 移除 000 後的內容:"+set1);
System.out.println("集合set1 中是否包含000 :"+set1.contains("000"));
System.out.println("集合set1 中是否包含111 :"+set1.contains("111"));
Set set2=new HashSet();
set2.add("111");
set2.addAll(set1);//將set1 集合中的元素全部都加到set2 中
System.out.println("集合set2 的內容:"+set2);
set2.clear();//清空集合 set1 中的元素
System.out.println("集合set2 是否爲空:"+set2.isEmpty());
Iterator iterator = set1.iterator();//得到一個迭代器
while (iterator.hasNext()) {//遍歷
Object element = iterator.next();
System.out.println("iterator = " + element);
}
//將集合set1 轉化爲數組
Object s[]= set1.toArray();
for(int i=0;i<s.length;i++){
System.out.println(s[i]);
}
}
}
4.configuration
package configuration;
public class ConfigTest {
/**
* Configuration配置文件測試
*/
public static void main(String[] args) {
String name=new ConfigUtil("config.properties").getValue("name");
System.out.println(name);
}
}
package configuration;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 讀取properties配置文件
*/
public class ConfigUtil {
private Properties propertie;
private InputStream inputFile;
/**
* 初始化Configuration類
*/
public ConfigUtil()
{
propertie = new Properties();
}
/**
* 初始化Configuration類
* @param filePath 要讀取的配置文件的路徑+名稱
*/
public ConfigUtil(String filePath)
{
propertie = new Properties();
try {
inputFile = this.getClass().getClassLoader().getResourceAsStream(filePath);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) {
System.out.println("讀取屬性文件--->失敗!- 原因:文件路徑錯誤或者文件不存在");
ex.printStackTrace();
} catch (IOException ex){
System.out.println("裝載文件--->失敗!");
ex.printStackTrace();
}
}
/**
* 重載函數,得到key的值
* @param key 取得其值的鍵
* @return key的值
*/
public String getValue(String key)
{
if(propertie.containsKey(key)){
String value = propertie.getProperty(key);//得到某一屬性的值
return value;
}
else{
System.out.println("配置文件中不包含該鍵值對!");
return "";
}
}
}
5.DataType
package DataType;
public class CharTest {
/**
* @char類型
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char ch1 = 97 ;
char ch2 = 'a' ;
System.out.println("ch1 = "+ch1);
System.out.println("ch2 = "+ch2);
}
}
package DataType;
public class Default {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
byte num1 = 0;
short num2 = 0;
int num3 = 0;
long num4 = 0L;
float num5=0.0f;
double num6=0.0d;
char num7='\u0000';
System.out.println(num1);
System.out.println(num2);
System.out.println(num3);
System.out.println(num4);
System.out.println(num5);
System.out.println(num6);
System.out.println(num7);
}
}
package DataType;
public class DobleAndFloat {
/**
* @
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double num1 = 6.3e64D ; // 聲明num1爲double,其值爲-6.3×1064
double num2 = 5.34E16d ; // e也可以用大寫的E來取代
float num3 = 7.32E2f ; // 聲明num3爲float,並設初值爲7.32f
float num4 = 2.0E38f;
System.out.println(num1);
System.out.println(num2);
System.out.println(num3);
System.out.println(num4);
}
}
package DataType;
public class Escape {
/**
* @輸出雙引號等轉義字符
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char ch ='\"';
System.out.println(ch+"測試轉義字符!"+ch);
System.out.println("\"hello world!\"");
}
}
package DataType;
public class IntTest {
/**
* @整數數據類型
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long num =2147483648L; // 聲明一長整型變量
System.out.println("num="+num);
int x = java.lang.Integer.MAX_VALUE ;
System.out.println("x = "+x);
System.out.println("x + 1 = "+(x+1));
System.out.println("x + 2 = "+(x+2L));
System.out.println("x + 3 = "+((long)x+3));
}
}
6.file
package file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class CopyFile {
/**
* 文件拷貝和顯示文件列表
*/
public static void main(String[] args) {
String filePath1="D:/test/1/1.txt";
String filePath2="D:/test/2/2.txt";
String filePath3="D:/test/";
try {
copy(filePath1,filePath2);
//listFile(filePath3);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 文件拷貝
*/
public static void copy(String srcPath,String desPath) throws Exception{
String folderPath="D:/test/1/1";
File folder=new File(folderPath);
//folder.mkdir();
File srcFile=new File(srcPath);
File desFile=new File(desPath);
//srcFile.delete();
// BufferInputStream bis=new BufferInputStream(srcFile); //字節流
// BufferOutputStream bos=new BufferOutputStream(desPath); //字節流
FileInputStream fis= new FileInputStream(srcFile); //字節流
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr); //字符流
FileOutputStream fos= new FileOutputStream(desFile); //字節流
OutputStreamWriter ow=new OutputStreamWriter(fos);
BufferedWriter bw=new BufferedWriter(ow); //字符流
//PrintWriter pw=new PrintWriter(ow);
int c;
while((c=fis.read())!=-1){
bw.write(c);
}
bw.close();
fos.close();
}
/*
* 文件列表,包括文件夾中的文件
*/
private static void listFile(String path) throws Exception{
File file=new File(path);
File files[]=file.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
listFile(path+files[i].getName());
}
//System.out.println(files[i].getName());
//System.out.println(files[i].toString());
System.out.println(files[i].getPath());
}
}
}
package file;
public class Static {
static {
System.out.println(1111);
}
/**
* 外部類和主類(main類)執行順序
*/
public Static(){
System.out.println("主類的構造方法");
}
public static void main(String[] args) {
S.say();
new S().say2();
say3();
}
static class S{
public S(){
System.out.println("S的構造方法");
}
static void say(){
System.out.println("say hello");
}
void say2(){
System.out.println("say hello2");
}
}
static void say3(){
System.out.println("say hello3");
}
}
7.huiwen
package huiwen;
import java.applet.Applet;
import java.awt.Event;
import java.awt.Label;
import java.awt.TextField;
/**
* 迴文
* @author Bryant
*
*/
public class Huiwen extends Applet {
Label prompt;
TextField input;
int data;
public void init() {
prompt = new Label("輸入數字");
input = new TextField(4);
add(prompt);
add(input);
}
public boolean action(Event e, Object o) {
int data = Integer.parseInt(input.getText());
showStatus("");
input.setText("");
int count = 0;
String[] arr = new String[1000000];
while (data != 0) {
arr[count] = String.valueOf(data % 10);
data = data / 10;
count++;
}
int j = count - 1;
boolean flag = true;
for (int i = 0; i < count / 2; i++, j--) {
if (!arr[i].equals(arr[j])){
showStatus("不是迴文數");
flag = false;
}
}
if(flag){
showStatus("是迴文數");
}
repaint();
return true;
}
}
package huiwen;
import java.applet.Applet;
import java.awt.Event;
import java.awt.Label;
import java.awt.TextField;
/**
* 迴文(比第一個省內存)
* @author Bryant
*
*/
public class Huiwen2 extends Applet {
Label lable;
TextField input;
public void init() {
lable = new Label("輸入數字");
input = new TextField(100);
add(lable);
add(input);
}
public boolean action(Event e, Object o) {
String text = input.getText().trim();
showStatus("");
input.setText("");
StringBuilder sb = new StringBuilder(text);
if (sb.reverse().toString().equals(text)) {
showStatus("不是迴文數");
} else {
showStatus("是迴文數");
}
repaint();
return true;
}
}
8.innerclass
package innerclass;
/*
* 內部類的使用
*/
public class OuterClass {
int score=100;
void inst(){
Inner in=new Inner();
in.display();
}
public class Inner{ //內部類也可以通過創建對象從外部類之外被調用,只要將內部類聲明爲public即可
void display(){
String name="zhangsan";
System.out.println("score="+score);//內部類可以直接調用外部類的屬性
}
}
public static class Inner2{
void display(){
String name="zhangsan";
//System.out.println("score="+score); //用static也可以聲明內部類,用static聲明的內部類則變成外部類,
//但是用static聲明的內部類不能訪問非static的外部類屬性。
}
}
// void print(){
// System.out.println("name="+name); //外部類不能使用內部類的屬性
// }
}
package innerclass;
public class OuterClassTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OuterClass out=new OuterClass();
out.inst();
OuterClass.Inner innner=out.new Inner();
innner.display();//內部類也可以通過創建對象從外部類之外被調用,只要將內部類聲明爲public即可
}
}
package innerclass;
/*
* 在外部類方法中定義內部類
*/
public class OuterClass2 {
int score = 95;
void inst()
{
class Inner
{
void display()
{
System.out.println("成績: score = " + score);
}
}
Inner in = new Inner();
in.display();
}
}
package innerclass;
public class OuterClassTest2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
{
OuterClass2 outer = new OuterClass2();
outer.inst() ;
}
}
}
package innerclass;
/*
* 在方法中定義的內部類只能訪問方法中的final類型的局部變量,
* 因爲用final定義的局部變量相當於是一個常量,它的生命週期超出方法運行的生命週期.
*/
public class OuterClass3 {
int score = 95;
void inst(final int s)
{
final int temp = 20 ;
class Inner
{
void display()
{
System.out.println("成績: score = " + (score+s+temp));
}
}
Inner in = new Inner();
in.display();
}
}
package innerclass;
public class OuterClassTest3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OuterClass3 outer=new OuterClass3();
outer.inst(5);
}
}
package innerclass;
public class SetApple {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
apple a=new apple();
a.appleweight=0.5;
System.out.println("蘋果重1兩");
System.out.println(a.bite());
a.appleweight=5;
System.out.println("蘋果重5兩");
System.out.println(a.bite());
}
}
//內部類
class apple{
long applecolor;
double appleweight;
boolean eatup;
public boolean bite(){
if(appleweight<1){
System.out.println("蘋果已經吃完了");
eatup=true;
}else{
System.out.println("蘋果吃不下了");
eatup=false;
}
return eatup;
}
}
package innerclass;
public class TestExtend extends Employee {
/**
* @param args
*/
public TestExtend(String name,int salary){
super(name,salary);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("覆蓋的方法調用" + getSalary("張三",500));
System.out.println("繼承的方法調用" + getSalary2("李四",500));
System.out.println("覆蓋的方法調用" + getSalary("張三",10000));
System.out.println("繼承的方法調用" + getSalary2("李四",10000));
}
public static String getSalary(String name, int salary) //重寫父類的方法(覆蓋的方法)
{
String str;
if (salary>5000)
str = "名字" + name + "Salary: " + salary;
else
str = "名字" + name + "Salary:低於5000";
return str;
}
public String getSalary3(){
return getSalary();
}
};
class Employee //父類
{
//public String name;//
//public int salary;//
private String name;// 如果把 變量設爲private,即私有化變量,則需要增加構造函數初始化類
private int salary;//
public Employee(String _name,int _salary){
name=_name;
salary=_salary;
}
public static String getSalary(String name, int salary)
{
String str;
str = "名字" + name + "Salary: " + salary;
return str;
}
public static String getSalary2(String name, int salary)
{
String str;
str = "名字" + name + "Salary: " + salary;
return str;
}
public String getSalary(){
String str;
str = "名字" + name + "Salary: " + salary;
return str;
}
};
9.io
package io;
import java.io.*;
public class SystemIo {
/**
* @System.in
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int bytes = 0;
byte buf[] = new byte[255];
System.out.print("請輸入您的文本:");
try{
bytes = System.in.read(buf,0,255);
System.out.print(bytes);
System.out.println("");
String inStr = new String(buf,0,bytes);
System.out.println(inStr);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
10.local
package local;
import java.util.Locale;
public class LocaleList {
/**
* @param args
*/
public static void main(String[] args) {
//返回Java 所支持的全部國家和語言的數組
Locale[] localeList = Locale.getAvailableLocales();
//遍歷數組的每個元素,依次獲取所支持的國家和語言
for (int i = 0; i < localeList.length ; i++ )
//打印出所支持的國家和語言
System.out.println(localeList[i] .getDisplayCountry() + "=" +
localeList[i] .getCountry()+ " " +
localeList[i] .getDisplayLanguage() + "=" +localeList[i] .getLanguage());
}
}
11.main
package main;
public class MainMethod {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int j = args.length ;
if(j!=2)
{
System.out.println("輸入參數個數有錯誤!") ;
// 退出程序
System.exit(1) ;
}
for (int i=0;i<args.length ;i++ )
{
System.out.println(args[i]) ;
}
}
}
12.privatetest
package privatetest;
public class Change {
int x=0;
}
package privatetest;
public class ChangeTest {
/**
* @引用數據類型 傳遞修改值(改變值,值類型不改變)
* 在fun方法中所做的操作,是會影響原先的參數
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Change c = new Change() ;
c.x = 20 ;
fun(c) ;
System.out.println("x = "+c.x);
}
public static void fun(Change c1)
{
c1.x = 25 ;
}
}
package privatetest;
public class Person {
String name ;
int age ;
}
package privatetest;
/*
* 封裝
*/
public class PersonPrivate {
private String name ;
private int age ;
private static void talk()
{
//System.out.println("我是:"+name+",今年:"+age+"歲");
}
public void say()
{
talk();
}
public void setName(String str)
{
name = str ;
}
public void setAge(int a)
{
if(a>0)
age = a ;
}
public String getName()
{
return name ;
}
public int getAge()
{
return age ;
}
}
package privatetest;
public class PersonTest {
/**
* @引用數據類型值傳遞(改變值)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 聲明一對象p1,此對象的值爲null,表示未實例化
Person p1 = null ;
// 聲明一對象p2,此對象的值爲null,表示未實例
Person p2 = null ;
// 實例化p1對象
p1 = new Person() ;
// 爲p1對象中的屬性賦值
p1.name = "張三" ;
p1.age = 25 ;
// 將p1的引用賦給p2
p2 = p1 ;
// 輸出p2對象中的屬性
System.out.println("姓名:"+p2.name);
System.out.println("年齡:"+p2.age);
//p2=null;
p1 = null ;
// System.out.println("姓名:"+p1.name);
// System.out.println("年齡:"+p1.age);
p2.name="李四";
System.out.println("姓名:"+p2.name);
}
}
package privatetest;
/*
* 構造方法私有化
*/
public class PublicToPrivate {
private PublicToPrivate()
{
System.out.println("private TestSingleDemo1 .") ;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new PublicToPrivate() ;
}
}
13.randow
package randow;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Randow {
/**
* 生成隨機數
*/
public static void main(String[] args) {
// int[] ints = new int[100];
// for(int i=0;i<100;i++) {
// int temp = (int) (Math.random()*100+1);
// for(int j=0;j<i;j++) {
// if(temp==ints[j]) {
// temp = (int) (Math.random()*100+1);
// j=0;
// }
// }
// ints[i]=temp;
// }
// Arrays.sort(ints);
// for(int index:ints) {
// if(index%10==0)
// System.out.println();
// System.out.print(index+" ");
// }
//隨機生成不重複的兩位數
String result="";
String str[]={"0","1","2","3","4","5","6","7","8","9"};
Random r=new Random();
while(result.length()<=1){
int i=r.nextInt(10);
if(result.indexOf(str[i])==-1){
result=result+str[i];
}
}
// System.out.println(result);
validateCode(2);
getNum();
random2();
}
//生產2位隨機數
public static void validateCode(int code_len) {
int count = 0;
char str[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
StringBuffer pwd = new StringBuffer("");
Random r = new Random();
while (count < code_len) {
int i = Math.abs(r.nextInt(10));
//int j = Math.abs(r.nextInt(10));
if (i >= 0 && i < str.length) {
pwd.append(str[i]);
count++;
}
}
// System.out.println(pwd.toString());
String pwd2="";
//return pwd.toString();
}
/**
* 產生兩位不重複的隨機數
*
* @return
*/
protected static void getNum() {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 99; i++) {
String key = i < 10 ? "0" + i : i + "";
map.put(key, key);
}
String num = getRandom();
if (map.containsKey(num)) {
getNum();
}else{
System.out.println(num);
}
}
public static String getRandom() {
String str = "";
Random random = new Random();
int num = random.nextInt(100);
if (num < 10) {
str = "0" + num;
} else {
str = num + "";
}
//System.out.println(str);
return str;
}
public static int[] random2(){
int send[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21};
int temp1,temp2,temp3;
Random r=new Random();
for(int i=0;i<send.length;i++){
temp1=Math.abs(r.nextInt())%(send.length-1);
temp2=Math.abs(r.nextInt())%(send.length-1);
if(temp1!=temp2){
temp3=send[temp1];
send[temp1]=send[temp2];
send[temp2]=temp3;
}
}
//System.out.println(send);
return send;
}
}
14.recursion
package recursion;
public class RecursionTest {
/**
* 遞歸
* @param args
*/
int sum=0;
int a=0;
public void sum(){
sum+=a;
a+=1;
if(a<5){
sum();
}
}
public static void main(String[] args) {
RecursionTest test=new RecursionTest();
test.sum();
System.out.println("計算結果爲:"+test.sum);
}
}
15.statictest
package statictest;
/*
* static靜態變量的使用
*/
public class Person {
String name ;
static String city = "中國";
int age ;
static int count=0 ;
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String talk()
{
return "我是:"+this.name+",今年:"+this.age+"歲,來自:"+city;
}
public Person()
{
count++ ; // 增加了一個對象
System.out.println("產生了:"+count+"個對象!");
talk();
}
}
package statictest;
public class StaticPersonTest {
/**
* static 靜態變量修改的是所有對象的屬性
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("張三",25) ;
Person p2 = new Person("李四",30) ;
Person p3 = new Person("王五",35) ;
System.out.println("修改之前信息:"+p1.talk()) ;
System.out.println("修改之前信息:"+p2.talk()) ;
System.out.println("修改之前信息:"+p3.talk()) ;
System.out.println(" ************* 修改之後信息 **************");
// 修改後的信息
p1.city = "美國" ;
p1.name="wangliu";
//只有靜態變量纔可以用類名直接調用
//Person.city="呵呵";
System.out.println("修改之後信息:"+p1.talk()) ;
System.out.println("修改之後信息:"+p2.talk()) ;
System.out.println("修改之後信息:"+p3.talk()) ;
new Person().talk();
//new Person();
}
}
package statictest;
/*
* 靜態方法的使用(靜態方法調用的變量只能是靜態的),靜態方法調用非靜態方法必須實例化
*/
public class Person2 {
String name ;
private static String city = "中國";
int age ;
public Person2(String name,int age)
{
this.name = name ;
this.age = age ;
}
public Person2()
{
}
//靜態變量既可以在靜態方法中使用,也可在非靜態方法中使用。
public String talk()
{
return "我是:"+this.name+",今年:"+this.age+"歲,來自:"+city;
//return null;
//非靜態方法不能調用靜態方法(錯,可以)
//setCity("");
}
public void talk2(){
setCity("");
}
public static void setCity(String c)
{
//靜態方法中不能使用this
//this.city=c;
//靜態方法調用的變量只能是靜態的
//name=c;
city = c ;
//靜態方法調用非靜態方法必須實例化
new Person2().talk();
}
}
package statictest;
public class StaticPersonTest2 {
/**
* static 靜態方法的調用
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person2 p1 = new Person2("張三",25) ;
Person2 p2 = new Person2("李四",30) ;
Person2 p3 = new Person2("王五",35) ;
System.out.println("修改之前信息:"+p1.talk()) ;
System.out.println("修改之前信息:"+p2.talk()) ;
System.out.println("修改之前信息:"+p3.talk()) ;
System.out.println(" ************* 修改之後信息 **************");
// 修改後的信息
//p1.city = "美國" ;
//只有靜態變量纔可以用類名直接調用
Person.city="呵呵";
Person2.setCity("美國") ;
System.out.println("修改之後信息:"+p1.talk()) ;
System.out.println("修改之後信息:"+p2.talk()) ;
System.out.println("修改之後信息:"+p3.talk()) ;
//調用類的方法是調用無參的構造方法,或者不寫構造方法,直接實例化後調用
new Person2().talk();
}
}
package statictest;
/*
* 靜態代碼塊(首先被執行)
*/
public class Person3 {
public Person3()
{
System.out.println("1.public Person()");
}
// 此段代碼會首先被執行
static
{
System.out.println("2.Person類的靜態代碼塊被調用!");
}
}
package statictest;
/*
* 靜態代碼塊首先被執行
*/
public class StaticPersonTest3 {
static
{
System.out.println("3.TestStaticDemo5類的靜態代碼塊被調用!");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("4.程序開始執行!");
// 產生兩個實例化對象
new Person3() ;
}
}
16.string
package string;
public class StringDemo {
/**
* 由程序輸出結果可以發現,str1與str3相等,這是爲什麼呢?
* 還記得上面剛提到過“==”是用來比較內存地址值的。現在str1與str3相等,則證明str1與str3是指向同一個內存空間的。
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = "java" ;
String str2 = new String("java") ;
String str3 = "java" ;
System.out.println("str1 == str2 ? --- > "+(str1==str2)) ;
System.out.println("str1 == str3 ? --- > "+(str1==str3)) ;
System.out.println("str3 == str2 ? --- > "+(str3==str2)) ;
}
}
package string;
public class StringTest1 {
/**
* ==號比較內存地址值是否相同
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = new String("java") ;
String str2 = new String("java") ;
String str3 = str2 ;
if(str1==str2)
{
System.out.println("str1 == str2");
}
else
{
System.out.println("str1 != str2") ;
}
if(str2==str3)
{
System.out.println("str2 == str3");
}
else
{
System.out.println("str2 != str3") ;
}
}
}
package string;
public class StringTest2 {
/**
* equals比較2個對象的內容是否一致
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = new String("java") ;
String str2 = new String("java") ;
String str3 = str2 ;
if(str1.equals(str2))
{
System.out.println("str1 equals str2");
}
else
{
System.out.println("str1 not equals str2") ;
}
if(str2.equals(str3))
{
System.out.println("str2 equals str3");
}
else
{
System.out.println("str2 note equals str3") ;
}
}
}
17.supertest
package supertest;
/*
* 繼承
*/
public class Person {
String name;
int age;
public Person()
{
System.out.println("1.public Person(){}") ;
}
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public void talk(){
}
}
package supertest;
public class Student extends Person {
String school ;
// 子類的構造方法
public Student()
{
super("張三",25);
System.out.println("2.public Student(){}");
}
}
package supertest;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s = new Student() ;
s.school="北京";
System.out.println("姓名:"+s.name+",年齡:"+s.age+",學校:"+s.school);
}
}
18.test
package test;
public class EqualsTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="hello";
String s2="hello";
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
String s3=new String("hello");
String s4=new String("hello");
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
char b=97;
System.out.println(b);
}
}
19.thistest
package thistest;
/*
* this 調用構造方法,只能放在首行
*/
public class Person {
String name ;
int age ;
public Person()
{
System.out.println("1. public Person()");
}
public Person(String name,int age){
// 調用本類中無參構造方法
this() ;
this.name = name ;
this.age = age ;
System.out.println("2. public Person(String name,int age)");
}
}
package thistest;
public class ThisPersonTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Person("張三",25) ;
}
}
20.thread
package thread;
public class MyThread {
/**
* 主線程
*/
public static void main(String[] args) {
ThreadDemo t1=new ThreadDemo("實例線程1");
t1.startthread();
//t1.runthread();
ThreadDemo t2=new ThreadDemo("實例線程2");
t2.startthread();
//t2.runthread();
}
}
package thread;
public class ThreadDemo extends Thread {
Thread thread;
String str;
//構造函數
public ThreadDemo(String str1){
this.str=str1;
}
//啓動線程
public void startthread(){
thread=new Thread(this);
thread.start();
}
public void runthread(){
int i=0;
while(thread!=null){
try{
if(i==5)
sleep(10000);
}catch(Exception e){
System.out.print(e.getMessage());
}
System.out.println(str);
i++;
}
}
}
package thread;
public class TwoThreadDemo extends Thread {
//String name;
/**
* 靜態方法調用非靜態方法必須實例化
*/
public static void main(String[] args) {
TwoThreadDemo tt = new TwoThreadDemo();
tt.start();
for ( int i = 0; i < 3; i++ ) {
System.out.println("Main thread");
}
new TwoThreadDemo().run1();
run2();
}
// public TwoThreadDemo(String name){
// this.name=name;
// }
public void run() {
for ( int i = 0; i < 3; i++ ) {
System.out.println("Run thread");
}
}
public void run1() {
for ( int i = 0; i < 3; i++ ) {
System.out.println("New thread");
}
// run2();
}
public static void run2(){
for ( int i = 0; i < 3; i++ ) {
System.out.println("My thread");
}
}
}
package thread;
//設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1
//以下程序使用內部類實現線程,對j增減的時候沒有考慮順序問題
public class ThreadTest{
private int j;
public static void main(String args[]){
ThreadTest tt=new ThreadTest();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}
private synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
}
class Inc implements Runnable{
public void run(){
for(int i=0;i<100;i++){
inc();
}
}
}
class Dec implements Runnable{
public void run(){
for(int i=0;i<100;i++){
dec();
}
}
}
}