1.给定一个java.util.Date对象,如何转化为”2007-3-22 20:23:22”格式的字符串
/**
*将某个日期以固定格式转化成字符串
*@paramdate
*@returnstr
*/
public String dateToStr(java.util.Date date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
return str;
}
2.写一个方法,能够判断任意一个整数是否素数
/**
*判断任意一个整数是否素数
*@paramn
*@returnboolean
*/
publicboolean isPrimes(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n%i==0)
{
returnfalse;
}
}
returntrue;
}
3.写一个方法,输入任意一个整数,返回它的阶乘
/**
*获得任意一个整数的阶乘
*@paramn
*@returnn!
*/
publicint factorial(int n)
{
//递归
if(n==1)
{
return 1;
}
return n*factorial(n-1);
//非递归
// int multi = 1;
// for (int i = 2; i <= n; i++) {
// multi*=i;
// }
// return multi;
}
4.写一个方法,用二分查找法判断任意整数在任意整数数组里面是否存在,若存在就返回它在数组中的索引位置,不存在返回-1
/**
*二分查找特定整数在整型数组中的位置(递归)
*@paramdataset
*@paramdata
*@parambeginIndex
*@paramendIndex
*@returnindex
*/
publicint binarySearch(int[] dataset,int data,int beginIndex,int endIndex)
{
int midIndex = (beginIndex+endIndex)/2;
if(data <dataset[beginIndex] | |data>dataset[endIndex] | |beginIndex>endIndex)return -1;
if(data <dataset[midIndex])
{
return binarySearch(dataset,data,beginIndex,midIndex-1);
}elseif(data>dataset[midIndex])
{
return binarySearch(dataset,data,midIndex+1,endIndex);
}else
{
return midIndex;
}
}
/**
*二分查找特定整数在整型数组中的位置(非递归)
*@paramdataset
*@paramdata
*@returnindex
*/
publicint binarySearch(int[] dataset ,int data)
{
int beginIndex = 0;
int endIndex = dataset.length - 1;
int midIndex = -1;
if(data <dataset[beginIndex] | |data>dataset[endIndex] | |beginIndex>endIndex)return -1;
while(beginIndex <= endIndex) {
midIndex = (beginIndex+endIndex)/2;
if(data <dataset[midIndex]) {
endIndex = midIndex-1;
} elseif(data>dataset[midIndex]) {
beginIndex = midIndex+1;
}else
{
return midIndex;
}
}
return -1;
}
5.做一个饲养员给动物喂食物的例子体现JAVA中的面向对象思想,接口(抽象类)的用处
package com.softeem.demo; /**
*@authorleno
*动物的接口
*/
interface Animal
{
publicvoid eat(Food food);
}
/**
*@authorleno
*一种动物类:猫
*/
class Cat implements Animal
{
publicvoid eat(Food food)
{
System.out.println("小猫吃"+food.getName());
}
}
/**
*@authorleno
*一种动物类:狗
*/
class Dog implements Animal
{
publicvoid eat(Food food)
{
System.out.println("小狗啃"+food.getName());
}
} /**
*@authorleno
*食物抽象类
*/
abstractclass Food
{
protected String name;
public String getName() {
returnname;
} publicvoid setName(String name) {
this.name = name;
}
} /**
*@authorleno
*一种食物类:鱼
*/
class Fish extends Food
{
public Fish(String name) {
this.name = name;
}
}
/**
*@authorleno
*一种食物类:骨头
*/
class Bone extends Food
{
public Bone(String name) {
this.name = name;
}
} /**
*@authorleno
*饲养员类
*
*/
class Feeder
{
/**
*饲养员给某种动物喂某种食物
*@paramanimal
*@paramfood
*/
publicvoid feed(Animal animal,Food food)
{
animal.eat(food);
}
} /**
*@authorleno
*测试饲养员给动物喂食物
*/
publicclass TestFeeder { publicstaticvoid main(String[] args) {
Feeder feeder=new Feeder();
Animal animal=new Dog();
Food food=new Bone("肉骨头");
feeder.feed(animal,food); //给狗喂肉骨头
animal=new Cat();
food=new Fish("鱼");
feeder.feed(animal,food); //给猫喂鱼 }
}
6.描述JAVA中异常处理的机制
? 程序的执行过程中如出现异常,会自动生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。Java
? 当Java运行时系统接收到异常对象时,会寻找能处理这一异常的代码并把当前异常对象交给其处理,这一过程称为捕获(catch)异常。
? 如果Java运行时系统找不到可以捕获异常的方法,则运行时系统将终止,相应的Java程序也将退出。
? 程序员通常只能处理违例(Exception),而对错误(Error)无能为力。 7.做一个单子模式的类,只加载一次属性文件
package com.softeem.demo; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; /**
*@authorleno
*单子模式,保证在整个应用期间只加载一次配置属性文件
*/
publicclass Singleton { privatestatic Singleton instance;
privatestaticfinal String CONFIG_FILE_PATH = "E://config.properties";
private Properties config;
private Singleton()
{
config = new Properties();
InputStream is;
try {
is = new FileInputStream(CONFIG_FILE_PATH);
config.load(is);
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publicstatic Singleton getInstance()
{
if(instance==null)
{
instance = new Singleton();
}
returninstance;
}
public Properties getConfig() {
returnconfig;
}
publicvoid setConfig(Properties config) {
this.config = config;
}
}
l J2SE
8.拷贝一个目录(文件)到指定路径
/**
*拷贝一个目录或者文件到指定路径下
*@paramsource
*@paramtarget
*/
publicvoid copy(File source,File target)
{
File tarpath = new File(target,source.getName());
if(source.isDirectory())
{
tarpath.mkdir();
File[] dir = source.listFiles();
for (int i = 0; i < dir.length; i++) {
copy(dir[i],tarpath);
}
}else
{
try {
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(tarpath);
byte[] buf = newbyte[1024];
int len = 0;
while((len = is.read(buf))!=-1)
{
os.write(buf,0,len);
}
is.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
9.用JAVA中的多线程示例银行取款问题
packagecom.softeem.demo; /**
*@authorleno
*账户类
*默认有余额,可以取款
*/
class Account {
privatefloatbalance = 1000; publicfloat getBalance() {
returnbalance;
} publicvoid setBalance(float balance) {
this.balance = balance;
}
/**
*取款的方法需要同步
*@parammoney
*/
publicsynchronizedvoid withdrawals(float money)
{
if(balance>=money)
{
System.out.println("被取走"+money+"元!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
balance-=money;
}
else
{
System.out.println("对不起,余额不足!");
}
}
} /**
*@authorleno
*银行卡
*/
class TestAccount1 extends Thread { private Account account;
public TestAccount1(Account account) {
this.account = account;
} @Override
publicvoid run() {
account.withdrawals(800);
System.out.println("余额为:"+account.getBalance()+"元!");
}
}
/**
*@authorleno
*存折
*/
class TestAccount2 extends Thread { private Account account;
public TestAccount2(Account account) {
this.account = account;
}
@Override
publicvoid run() {
account.withdrawals(700);
System.out.println("余额为:"+account.getBalance()+"元!");
}
} publicclass Test
{
publicstaticvoid main(String[] args) {
Account account = new Account();
TestAccount1 testAccount1 = new TestAccount1(account);
testAccount1.start();
TestAccount2 testAccount2 = new TestAccount2(account);
testAccount2.start();
}
}
10.用JAVA中的多线程示例火车站售票问题
package com.softeem.demo; /**
*@authorleno
*售票类
*/
class SaleTicket implements Runnable {
inttickets = 100; publicvoid run() {
while (tickets > 0) {
sale();
//或者下面这样实现
// synchronized (this) {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "卖第"
// + (100 - tickets + 1) + "张票");
// tickets--;
// }
// }
}
} publicsynchronizedvoid sale() {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "卖第"
+ (100 - tickets + 1) + "张票");
tickets--;
}
} }
publicclass TestSaleTicket {
publicstaticvoid main(String[] args) {
SaleTicket st = new SaleTicket();
new Thread(st, "一号窗口").start();
new Thread(st, "二号窗口").start();
new Thread(st, "三号窗口").start();
new Thread(st, "四号窗口").start(); }
} 11.用JAVA中的多线程示例生产者和消费者问题
package com.softeem.demo; class Producer implements Runnable
{
private SyncStack stack; public Producer(SyncStack stack) {
this.stack = stack;
} publicvoid run() {
for (int i = 0; i < stack.getProducts().length; i++) {
String product = "产品"+i;
stack.push(product);
System.out.println("生产了: "+product);
try
{
Thread.sleep(200);
}
catch(InterruptedException e)
{
e.printStackTrace();
} }
}
} class Consumer implements Runnable
{
private SyncStack stack; public Consumer(SyncStack stack) {
this.stack = stack;
}
publicvoid run() {
for(int i=0;i <stack.getProducts().length;i++)
{
String product =stack.pop();
System.out.println("消费了: "+product);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
} }
}
} class SyncStack
{
private String[] products = new String[10];
privateintindex;
publicsynchronizedvoid push(String product)
{
if(index==product.length())
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
products[index]=product;
index++;
}
publicsynchronized String pop()
{
if(index==0)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
index--;
String product = products[index];
return product;
} public String[] getProducts() {
returnproducts;
}
}
publicclass TestProducerConsumer {
publicstaticvoid main(String[] args) {
SyncStack stack=new SyncStack();
Producer p=new Producer(stack);
Consumer c=new Consumer(stack); new Thread(p).start();
new Thread(c).start();
}
}