重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
//主类EnglishTest——
创新互联专注于中大型企业的成都做网站、网站设计和网站改版、网站营销服务,追求商业策划与数据分析、创意艺术与技术开发的融合,累计客户数千家,服务满意度达97%。帮助广大客户顺利对接上互联网浪潮,准确优选出符合自己需要的互联网运用,我们将一直专注品牌网站制作和互联网程序开发,在前进的路上,与客户一起成长!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EnglishTest extends JFrame
{
TestArea testPanel=null;
Container con=null;
public EnglishTest()
{
super("模拟考试");
testPanel=new TestArea();
con=getContentPane();
con.add(testPanel,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setVisible(true);
setBounds(60,40,660,460);
con.validate();
validate();
}
public static void main(String args[])
{
new EnglishTest();
}
}
//读取试题 ReadTestquestion
import java.io.*;
import java.util.*;
public class ReadTestquestion
{ String filename="",
correctAnswer="",
testContent="" ,
selection="" ;
int score=0;
long time=0;
boolean 完成考试=false;
File f=null;
FileReader in=null;
BufferedReader 读取=null;
public void setFilename(String name)
{ filename=name;
score=0;
selection="";
try {
if(in!=null读取!=null)
{
in.close();
读取.close();
}
f=new File(filename);
in=new FileReader(f);
读取=new BufferedReader(in);
correctAnswer=(读取.readLine()).trim();
String temp=(读取.readLine()).trim() ;
StringTokenizer token=new StringTokenizer(temp,":");
int hour=Integer.parseInt(token.nextToken()) ;
int minute=Integer.parseInt(token.nextToken());
int second=Integer.parseInt(token.nextToken());
time=1000*(second+minute*60+hour*60*60);
}
catch(Exception e)
{
testContent="没有选择试题";
}
}
public String getFilename()
{
return filename;
}
public long getTime()
{
return time;
}
public void set完成考试(boolean b)
{
完成考试=b;
}
public boolean get完成考试()
{
return 完成考试;
}
public String getTestContent()
{ try {
String s=null;
StringBuffer temp=new StringBuffer();
if(读取!=null)
{
while((s=读取.readLine())!=null)
{
if(s.startsWith("**"))
break;
temp.append("\n"+s);
if(s.startsWith("endend"))
{
in.close();
读取.close();
完成考试=true;
}
}
testContent=new String(temp);
}
else
{
testContent=new String("没有选择试题");
}
}
catch(Exception e)
{
testContent="试题内容为空,考试结束!!";
}
return testContent;
}
public void setSelection(String s)
{
selection=selection+s;
}
public int getScore()
{ score=0;
int length1=selection.length();
int length2=correctAnswer.length();
int min=Math.min(length1,length2);
for(int i=0;imin;i++)
{ try{
if(selection.charAt(i)==correctAnswer.charAt(i))
score++;
}
catch(StringIndexOutOfBoundsException e)
{
i=0;
}
}
return score;
}20:10 03-8-31
public String getMessages()
{
int length1=selection.length();
int length2=correctAnswer.length();
int length=Math.min(length1,length2);
String message="正确答案:"+correctAnswer.substring(0,length)+"\n"+
"你的回答:"+selection+"\n";
return message;
}
}
//考试区域TestArea
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class FileName implements FilenameFilter
{
String str=null;
FileName (String s)
{
str="."+s;
}
public boolean accept(File dir,String name)
{
return name.endsWith(str);
}
}
public class TestArea extends JPanel implements ActionListener,ItemListener,Runnable
{
Choice list=null;
JTextArea 试题显示区=null,消息区=null;
JCheckBox box[];
JButton 提交该题答案,读取下一题,查看分数;
ReadTestquestion 读取试题=null;
JLabel welcomeLabel=null;
Thread countTime=null;
long time=0;
JTextField timeShow=null;
boolean 是否关闭计时器=false,
是否暂停计时=false;
JButton 暂停或继续计时=null;
public TestArea()
{
list= new Choice();
String 当前目录=System.getProperty("user.dir");
File dir=new File(当前目录);
FileName fileTxt=new FileName("txt");
String fileName[]=dir.list(fileTxt);
for(int i=0;ifileName.length;i++)
{
list.add(fileName[i]);
}
试题显示区=new JTextArea(15,12);
试题显示区.setLineWrap(true);
试题显示区.setWrapStyleWord(true);
试题显示区.setFont(new Font("TimesRoman",Font.PLAIN,14));
试题显示区.setForeground(Color.blue);
消息区=new JTextArea(8,8);
消息区.setForeground(Color.blue);
消息区.setLineWrap(true);
消息区.setWrapStyleWord(true);
countTime=new Thread(this);
String s[]={"A","B","C","D"};
box=new JCheckBox[4];
for(int i=0;i4;i++)
{
box[i]=new JCheckBox(s[i]);
}
暂停或继续计时=new JButton("暂停计时");
暂停或继续计时.addActionListener(this);
提交该题答案=new JButton("提交该题答案");
读取下一题=new JButton("读取第一题");
读取下一题.setForeground(Color.blue);
提交该题答案.setForeground(Color.blue);
查看分数=new JButton("查看分数");
查看分数.setForeground(Color.blue);
提交该题答案.setEnabled(false);
提交该题答案.addActionListener(this);
读取下一题.addActionListener(this);
查看分数.addActionListener(this);
list.addItemListener(this);
读取试题=new ReadTestquestion();
JPanel pAddbox=new JPanel();
for(int i=0;i4;i++)
{
pAddbox.add(box[i]);
}
Box boxH1=Box.createVerticalBox(),
boxH2=Box.createVerticalBox(),
baseBox=Box.createHorizontalBox();
boxH1.add(new JLabel("选择试题文件"));
boxH1.add(list);
boxH1.add(new JScrollPane(消息区));
boxH1.add(查看分数);
timeShow=new JTextField(20);
timeShow.setHorizontalAlignment(SwingConstants.RIGHT);
timeShow.setEditable(false);
JPanel p1=new JPanel();
p1.add(new JLabel("剩余时间:"));
p1.add(timeShow);
p1.add(暂停或继续计时);
boxH1.add(p1);
boxH2.add(new JLabel("试题内容:"));
boxH2.add(new JScrollPane(试题显示区));
JPanel p2=new JPanel();
p2.add(pAddbox);
p2.add(提交该题答案);
p2.add(读取下一题);
boxH2.add(p2);
baseBox.add(boxH1);
baseBox.add(boxH2);
setLayout(new BorderLayout());
add(baseBox,BorderLayout.CENTER);
welcomeLabel=new JLabel("欢迎考试,提高英语水平",JLabel.CENTER);
welcomeLabel.setFont(new Font("隶书",Font.PLAIN,24));
welcomeLabel.setForeground(Color.blue);
add(welcomeLabel,BorderLayout.NORTH);
}
public void itemStateChanged(ItemEvent e)
{
timeShow.setText(null);
是否关闭计时器=false;
是否暂停计时=false;
暂停或继续计时.setText("暂停计时");
String name=(String)list.getSelectedItem();
读取试题.setFilename(name);
读取试题.set完成考试(false);
time=读取试题.getTime();
if(countTime.isAlive())
{
是否关闭计时器=true;
countTime.interrupt();
}
countTime=new Thread(this);
消息区.setText(null);
试题显示区.setText(null);
读取下一题.setText("读取第一题");
提交该题答案.setEnabled(false);
读取下一题.setEnabled(true);
welcomeLabel.setText("欢迎考试,你选择的试题:"+读取试题.getFilename());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==读取下一题)
{
读取下一题.setText("读取下一题");
提交该题答案.setEnabled(true);
String contentTest=读取试题.getTestContent();
试题显示区.setText(contentTest);
消息区.setText(null);
读取下一题.setEnabled(false);
try {
countTime.start();
}
catch(Exception event)
{
}
}
if(e.getSource()==提交该题答案)
{
读取下一题.setEnabled(true);
提交该题答案.setEnabled(false);
String answer="?";
for(int i=0;i4;i++)
{
if(box[i].isSelected())
{
answer=box[i].getText();
box[i].setSelected(false);
break;
}
}
读取试题.setSelection(answer);
}
if(e.getSource()==查看分数)
{
int score=读取试题.getScore();
String messages=读取试题.getMessages();
消息区.setText("分数:"+score+"\n"+messages);
}
if(e.getSource()==暂停或继续计时)
{
if(是否暂停计时==false)
{
暂停或继续计时.setText("继续计时");
是否暂停计时=true;
}
else if(是否暂停计时==true)
{
暂停或继续计时.setText("暂停计时");
是否暂停计时=false;
countTime.interrupt();
}
}
}
public synchronized void run()
{
while(true)
{
if(time=0)
{
是否关闭计时器=true;
countTime.interrupt();
提交该题答案.setEnabled(false);
读取下一题.setEnabled(false);
timeShow.setText("用时尽,考试结束");
}
else if(读取试题.get完成考试())
{
是否关闭计时器=true;
timeShow.setText("考试效果:分数*剩余时间(秒)="+1.0*读取试题.getScore()*(time/1000));
countTime.interrupt();
提交该题答案.setEnabled(false);
读取下一题.setEnabled(false);
}
else if(time=1)
{
time=time-1000;
long leftTime=time/1000;
long leftHour=leftTime/3600;
long leftMinute=(leftTime-leftHour*3600)/60;
long leftSecond=leftTime%60;
timeShow.setText(""+leftHour+"小时"+leftMinute+"分"+leftSecond+"秒");
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException ee)
{
if(是否关闭计时器==true)
return ;
}
while(是否暂停计时==true)
{
try
{
wait();
}
catch(InterruptedException ee)
{
if(是否暂停计时==false)
{
notifyAll();
}
}
}
}
}
}
用Calendar类里面的add(int field, int amount) 方法进行时间的计算。示例代码如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TestCalendar {
public static void main(String[] args){
Calendar c = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
c.setTime(format.parse("2011-08-05 14:49:45"));
System.out.println("原来的时间:"+format.format(c.getTime()));
c.add(Calendar.MINUTE,20);
System.out.println("计算后得到的时间:"+format.format(c.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
如果今天是2011年1月5日,先引入import java.util.Date;import java.text.SimpleDateFormat;
Date time=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(time);//日历为今天
long tm,tm1;
tm=cal.getTimeInMillis();//得到当前时间与1970年1月1日0点相距的毫秒数
tm1=tm-(24*60*60*1000);//得到昨天与1970年1月1日0点相距的毫秒数
Date time1=new Date(tm1);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String tm=sdf.format(time1);//tm就是昨天的日期的字符串表示
jsp页面做一个倒计时的提示就可以控制时间了。
实现方法如下:
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%
div id="showTimes"/div
%
long current_time=System.currentTimeMillis();
long end_time=1337875200000l;
long time=end_time-current_time;
%
script
var second = %= time / 1000%; // 剩余秒数
// 写一个方法,将秒数专为天数
var toDays = function(){
var s = second % 60; // 秒
var mi = (second - s) / 60 % 60; // 分钟
var h = ((second - s) / 60 - mi ) / 60 % 24; // 小时
var d = (((second - s) / 60 - mi ) / 60 - h ) / 24 // 天
return "剩余:" + d + "天" + h + "小时" + mi + "分钟" + s + "秒";
}
//然后写一个定时器
window.setInterval(function(){
second --;
document.getElementById("showTimes").innerHTML = toDays ();
}, 1000);
/script
第一种是以毫秒为单位计算的。
[java] view plaincopy
//伪代码
long startTime=System.currentTimeMillis(); //获取开始时间
doSomeThing(); //测试的代码段
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(end-start)+"ms");
第二种是以纳秒为单位计算的。
[java] view plaincopy
//伪代码
long startTime=System.nanoTime(); //获取开始时间
doSomeThing(); //测试的代码段
long endTime=System.nanoTime(); //获取结束时间
System.out.println("程序运行时间: "+(end-start)+"ns");
提供一个时间操作类给你,你可以调用里面的dateDiff方法,dateDiff(new Date(), getDateFromString("明天的字符串")表示的就是现在到明天0点之前的差距天数。
你要分钟数的话就自己改一下dateDiff,不要除以60和24就是分钟了
以下是工具类代码
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AdDateUtil {
private static Logger logger = Logger.getLogger(AdDateUtil.class);
static public String getNowStr(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String now = sdf.format(new Date());
return now;
}
static public Date getFormatDate(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d = new Date();
try {
d = sdf.parse(date);
} catch (ParseException e) {
logger.error(e);
}
return d;
}
static public String getDateStr(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String d = sdf.format(date);
return d;
}
static public String getPadZeroString(String s, int size) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i (size - s.length()); i++) {
sb.append("0");
}
sb.append(s);
return sb.toString();
}
/**
* 得到某月的天数
*
* @param year
* @param month
* @return
*/
static public int getDayCountOfMonth(String year, String month) {
Calendar cal = Calendar.getInstance();
// 年
cal.set(Calendar.YEAR, Integer.parseInt(year));
// 月,因为Calendar里的月是从0开始,所以要-1
cal.set(Calendar.MONTH, Integer.parseInt(month) - 1);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
static public String getYesterday(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
Calendar now = Calendar.getInstance();
now.roll(Calendar.DAY_OF_YEAR, -1); //昨天
return df.format(now.getTime());
}
/**
* 获取和今天附近的某天
* @param format
* @param diff
* @return
*/
static public String getADay(String format, int diff) {
SimpleDateFormat df = new SimpleDateFormat(format);
Calendar now = Calendar.getInstance();
int beforeM = now.get(Calendar.MONTH);
now.roll(Calendar.DAY_OF_YEAR, diff); //
int nowM = now.get(Calendar.MONTH);
//必须进行日期处理,否则2009-01-04日前七天是2009-12-28
if (nowM beforeM) {
now.roll(Calendar.YEAR, -1);
}
return df.format(now.getTime());
}
static public String getTomorrow(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
Calendar now = Calendar.getInstance();
now.roll(Calendar.DAY_OF_YEAR, 1); //明天
return df.format(now.getTime());
}
/**
* 得到最近num天的全部日期
* 说明:
* 1.日期是从昨天开始算的.
* 2.如果num=2 , 日期是2008-03-14 ,则返回的结果为 2008-03-12、2008-03-13
* @param num
* @return
*/
public static String[] getDaysByNum(int num, String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String[] result = { };
Calendar cal = Calendar.getInstance();
cal.setTime(getDateFromString(date, "yyyy-MM-dd"));
//最近一周
result = new String[num];
for (int i = num; i 0; i--) {
cal.add(Calendar.DAY_OF_YEAR, -1);
result[i - 1] = sdf.format(new Date(cal.getTimeInMillis()));
}
return result;
}
public static Date getDateFromString(String dateStr, String format) {
if ((dateStr == null) || (format == null)) {
try {
throw new Exception("数据类型异常" + dateStr + "|" + format);
} catch (Exception e) {
logger.error("数据类型异常:" + e);
}
}
SimpleDateFormat df = new SimpleDateFormat(format);
Date date;
try {
date = df.parse(dateStr);
return date;
} catch (Exception ex) {
logger.error(ex);
return new Date();
}
}
static public int getNowYear() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.YEAR);
}
static public int getNowMonth() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.MONTH) + 1;
}
public static String[] getMonthRang(String year, String month) {
String beginDate = year + "-" + month + "-01";
String endDate = year + "-" + month + "-" +
getDayCountOfMonth(year, month);
return getDaysByRang(beginDate, endDate);
}
public static String[] getDaysByRang(String beginDate, String endDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//得到两个日期间相差多少天
int num = dateDiff(beginDate, endDate);
if (num 0) {
//颠倒一下日期
String tmp = beginDate;
beginDate = endDate;
endDate = tmp;
num = 0 - num;
}
String[] result = { };
Calendar cal = Calendar.getInstance();
try {
cal.setTime(sdf.parse(beginDate));
} catch (ParseException e) {
e.printStackTrace();
}
num = num + 1; //把开始和结束日期都包含进去
result = new String[num];
for (int i = 0; i num; i++) {
if (i 0) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
result[i] = sdf.format(new Date(cal.getTimeInMillis()));
}
return result;
}
public static int dateDiff(String beginDate, String endDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(endDate);
} catch (ParseException e) {
date = new Date();
e.printStackTrace();
}
long end = date.getTime();
try {
date = sdf.parse(beginDate);
} catch (ParseException e) {
date = new Date();
e.printStackTrace();
}
long begin = date.getTime();
long day = (end - begin) / (1000 * 3600 * 24); //除1000是把毫秒变成秒
return Integer.parseInt(Long.toString(day));
}
public static void main(String[] args) {
System.out.println(AdDateUtil.getADay("yyyy-MM-dd", -7));
}
}