若干个经典的Java小程序源代码
java经典程序100例

11、计算圆周率 PI=4-4/3+4/5-4/7....... 打印出第一个大于 3.1415 小于 3.1416 的值
class Pi { public static void main(String[] args){ double pi =0; //定义初始值 double fenZi = 4; //分子为 4 double fenMu = 1; //第一个 4,可看作分母为 1 的分式,以后的分母每次递增 2 for (int i = 0; i < 1000000000; i++){ //运行老久,减少循环次数会快很多,只是精确
int year; //定义输入的年份名字为“year” Scanner scanner = new Scanner(System.in); year = scanner.nextInt(); if (year<0||year>3000){
System.out.println("年份有误,程序退出!"); System.exit(0); } if ((year%4==0)&&(year%100!=0)||(year%400==0)) System.out.println(year+" is bissextile"); else System.out.println(year+" is not bissextile "); } }
12、输入一个数据 n,计算斐波那契数列(Fibonacci)的第 n 个值 1 1 2 3 5 8 13 21 34 规律:一个数等于前两个数之和
//计算斐波那契数列(Fibonacci)的第 n 个值 public class Fibonacci{
Java语言实现拼图游戏源代码

Java语言实现拼图游戏源代码/** JA V A小游戏-拼图我做的第一个小游戏* Cell类是继承的按钮类,并加上相应图形,形成方格*MyCanvas是一个面板,加载Cell类的对象(方格),是这三个类中的核心*/import java.awt.Rectangle;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Choice;import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Icon;import javax.swing.JButton;public class MyMainFrame extends JFrame implements ActionListener { MyCanvas myCanvas;JPanel panelNorth,panelPreview;//定义上方的面板,及预览所需的面板Button start,preview,set;//定义开始,预览,设定按钮Container container;//容器,得到内容面板public MyMainFrame() {//初使化container=this.getContentPane();start=new Button("开始");start.addActionListener(this);preview=new Button("预览");preview.addActionListener(this);set = new Button("设置");set.addActionListener(this);panelPreview=new JPanel();panelPreview.setLayout(null);Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.add(label);panelNorth=new JPanel();panelNorth.setBackground(Color.red);panelNorth.add(start);panelNorth.add(preview);panelNorth.add(set);myCanvas=new MyCanvas();container.add(myCanvas,BorderLayout.CENTER);container.add(panelNorth,BorderLayout.NORTH);this.setTitle("拼图小游戏-明");this.setLocation(300,200);this.setSize(308,365);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(3);}public static void main(String[] args) {// TODO 自动生成方法存根new MyMainFrame();}public void actionPerformed(ActionEvent arg0) {//对三个按钮事件的处理// TODO 自动生成方法存根Button button=(Button)arg0.getSource();if(button==start){myCanvas.Start();}else if(button==preview){if(button.getLabel()=="预览"){container.remove(myCanvas);container.add(panelPreview);panelPreview.updateUI();container.repaint();button.setLabel("返回");}else{container.remove(panelPreview);container.add(myCanvas);container.repaint();button.setLabel("预览");}}else if(button==set){//修改所选图片Choice pic = new Choice();pic.add("小猫");pic.add("小猪");pic.add("云");pic.add("QQ");pic.add("卡通");pic.add("花");int i=JOptionPane.showConfirmDialog(this, pic, "选择图片", JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){MyCanvas.pictureID=pic.getSelectedIndex()+1;myCanvas.reLoadPictrue();Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.removeAll();panelPreview.add(label);panelPreview.repaint();}}}}class MyCanvas extends JPanel implements MouseListener {boolean hasAddActionListener=false;//设置方格的动作监听器的标志位,TRUE为已经添加上动作事件,FALSE是尚未添加动作事件Cell cell[];//定义方格Rectangle cellNull;//定义空方格区域public static int pictureID=1;//当前选择的图片代号public MyCanvas() {this.setLayout(null);this.setSize(400,400);cellNull=new Rectangle(200,200,100,100);//空方格区域在第三行每三列cell=new Cell[9];Icon icon;for (int i = 0; i < 3; i++) {//为9个方格加载图片,并初使化坐标,形成三行三列for(int j=0;j<3;j++){icon=new ImageIcon("pic_"+pictureID+"_"+(i*3+j+1)+".jpg");cell[i*3+j]=new Cell(icon);cell[i*3+j].setLocation(j*100,i*100);this.add(cell[i*3+j]);}}this.remove(cell[8]);//移除最后一个多余的方格}文章转自上海青大实训:。
java优秀代码案例

java优秀代码案例
在Java中,有许多优秀的代码案例可供学习。
以下是一些例子:
1. Java Collections Framework: Java的集合框架是一个很好的例子,它展示了如何使用接口和抽象类来创建一个可扩展的系统。
Java集合框架主要
包括两种类型的集合:Collection和Map。
2. Java I/O 库: Java的I/O库也是非常值得学习的。
它提供了许多类和接口,用于处理文件输入和输出,网络通信,数据序列化等。
3. Spring框架: Spring框架是一个非常流行的Java框架,用于构建企业级应用程序。
它是一个开源的Java平台,提供了一种全面的编程和配置模型,用于构建企业级应用程序。
Spring框架的核心是依赖注入和面向切面编程。
4. JUnit: JUnit是一个Java编程语言的单元测试框架。
它用于对Java类进
行单元测试,并帮助开发人员编写可重复的测试。
JUnit是开源的,并且是
极限编程和许多其他方法论的核心工具。
5. Apache Commons Lang: Apache Commons Lang是一个Java核心库,提供了一些实用的工具类和实用程序,用于处理常见的Java类。
这个库包
括字符串处理,日期处理,数学等。
以上都是一些非常优秀的Java代码案例,可以帮助你提高编程技能和编写
更好的代码。
Java猜拳小游戏源代码

第一个文件:public class Computer {String name;int score;public int showfist(){int quan;quan=(int)(Math.random()*10);if(quan<=2){quan=1;}else if(quan<=5){quan=2;}else{quan=3;}switch(quan){case 1:System.out.println(name+"出拳:剪刀");break;case 2:System.out.println(name+"出拳:石头");break;case 3:System.out.println(name+"出拳:布");break;}return quan;}}第二个文件:import java.util.Scanner;public class Game {int count=0;int countP=0;Person person=new Person();Computer computer=new Computer();Scanner input=new Scanner(System.in);public void initial(){System.out.print("请选择你的角色(1.刘备 2.孙权 3.曹操):");int juese=input.nextInt();switch(juese){case 1:="刘备";break;case 2:="孙权";break;case 3:="曹操";break;}System.out.print("请选择对手角色(1.关羽 2.张飞 3.赵云):");int JueSe=input.nextInt();switch(JueSe){case 1:="关羽";break;case 2:="张飞";break;case 3:="赵云";break;}}public void begin(){System.out.print("\n要开始吗? (y/n)");String ans=input.next();if(ans.equals("y")){String answ;do{int a=person.showFist();int b=computer.showfist();if(a==1&&b==3||a==2&&b==1||a==3&&b==2){System.out.println("结果:你赢了!");person.score++;}else if(a==1&&b==1||a==2&&b==2||a==3&&b==3){System.out.println("结果:平局,真衰!嘿嘿,等着瞧吧!");countP++;}else{System.out.println("结果:你输了!");computer.score++;}count++;System.out.print("\n是否开始下一轮? (y/n)");answ=input.next();}while(answ.equals("y"));}}public String calcResult(){String a;if(person.score>computer.score){a="最终结果:恭喜恭喜!你赢了!";}else if(person.score==computer.score){a="最终结果:打成平手,下次再和你一决高下!";}else{a="最终结果:呵呵,你输了!笨笨,下次加油啊!";}return a;}public void showResult(){System.out.println("---------------------------------------------------");System.out.println("\t\t"++" VS"++"\n");System.out.println("对战次数:"+count+"次");System.out.println("平局:"+countP+"次");System.out.println(+"得:"+person.score+"分");System.out.println(+"得:"+computer.score+"分\n");System.out.println(calcResult());System.out.println("---------------------------------------------------");}}第三个文件:import java.util.Scanner;public class Person {String name;int score;Scanner input=new Scanner(System.in);public int showFist(){System.out.print("\n请出拳:1.剪刀2.石头3.布");int quan=input.nextInt();switch(quan){case 1:System.out.println("你出拳:剪刀");break;case 2:System.out.println("你出拳:石头");break;case 3:System.out.println("你出拳:布");break;}return quan;}}第四个文件:public class Test {public static void main(String[]args){Game g=new Game();System.out.println("-----------------欢迎进入游戏世界--------------------\n\n");System.out.println("\t\t******************");System.out.println("\t\t** 猜拳开始 **");System.out.println("\t\t******************\n\n");System.out.println("出拳规则:1.剪刀2.石头3.布");g.initial();g.begin();g.showResult();}}。
Java高效代码50例

Java⾼效代码50例摘⾃:导读 世界上只有两种物质:⾼效率和低效率;世界上只有两种⼈:⾼效率的⼈和低效率的⼈。
----萧伯纳常量&变量直接赋值常量,禁⽌声明新对象 直接赋值常量值,只是创建了⼀个对象引⽤,⽽这个对象引⽤指向常量值。
反例Long i=new Long(1L);String s=new String("abc");正例Long i=1L;String s="abc";当成员变量值⽆需改变时,尽量定义为静态常量 在类的每个对象实例中,每个成员变量都有⼀份副本,⽽成员静态常量只有⼀份实例。
反例public class HttpConnection{private final long timeout=5L;...}正例public class HttpConnection{private static final long timeout=5L;...}尽量使⽤基本数据类型,避免⾃动装箱和拆箱 Java中的基本数据类型double、float、long、int、short、char、boolean,分别对应包装类Double、Float、Long、Integer、Short、Character、Boolean。
Jvm⽀持基本类型与对象包装类的⾃动转换,被称为⾃动装箱和拆箱。
装箱和拆箱都是需要CPU和内存资源的,所以应尽量避免⾃动装箱和拆箱。
反例Integer sum = 0;int[] values = { 1, 2, 3, 4, 5 };for (int value : values) {sum+=value;}正例int sum = 0;int[] values = { 1, 2, 3, 4, 5 };for (int value : values) {sum+=value;}如果变量的初值会被覆盖,就没有必要给变量赋初值反例public static void main(String[] args) {boolean isAll = false;List<Users> userList = new ArrayList<Users>();if (isAll) {userList = userDAO.queryAll();} else {userList=userDAO.queryActive();}}public class Users {}public static class userDAO {public static List<Users> queryAll() {return null;}public static List<Users> queryActive() {return null;}}正例public static void main(String[] args) {boolean isAll = false;List<Users> userList;if (isAll) {userList = userDAO.queryAll();} else {userList=userDAO.queryActive();}}public class Users {}public static class userDAO {public static List<Users> queryAll() {return null;}public static List<Users> queryActive() {return null;}}尽量使⽤函数内的基本类型临时变量 在函数内,基本类型的参数和临时变量都保存在栈(Stack)中,访问速度较快;对象类型的参数和临时变量的引⽤都保存在栈(Stack)中,内容都保存在堆(Heap)中,访问速度较慢。
java 常用代码样版

java 常用代码样版在Java开发领域中,开发人员常常需要为业务需求编写各种代码,包括实现算法、数据库访问、网络通信等等。
为了提高开发效率以及代码的可读性,我们需要学会使用一些常用代码样板,这样可以避免重复的工作,也提高了代码的可维护性。
下面,我将为大家介绍几个常用的Java代码样板:一、单例模式样板```public class Singleton {private static Singleton instance = null;private Singleton() {}public static Singleton getInstance(){if(instance == null) {instance = new Singleton();}return instance;}}```二、静态工厂样板```public class StaticFactory {public static Product getProduct(String type) {if (type.equals("productA")) {return new ProductA();} else if (type.equals("productB")) {return new ProductB();} else {return null;}}}```三、工厂方法样板```public interface Factory {public Product getProduct();}public class ProductAFactory implements Factory { public Product getProduct() {return new ProductA();}}public class ProductBFactory implements Factory { public Product getProduct() {return new ProductB();}}```四、代理模式样板```public interface Subject {public void request();}public class RealSubject implements Subject {public void request() {System.out.println("真实对象的请求");}}public class Proxy implements Subject {private RealSubject realSubject;public Proxy() {}public void request() {if(realSubject == null) {realSubject = new RealSubject();}preRequest();realSubject.request();postRequest();}private void preRequest() {System.out.println("请求前的处理...");}private void postRequest() {System.out.println("请求后的处理...");}}```五、观察者模式样板```public interface Observer {public void update();}public class ConcreteObserver implements Observer { public void update() {System.out.println("接收到通知,开始更新自己..."); }}public interface Subject {public void attach(Observer observer);public void detach(Observer observer);public void notifyObservers();}public class ConcreteSubject implements Subject {private List<Observer> observers = newArrayList<Observer>();public void attach(Observer observer) {observers.add(observer);}public void detach(Observer observer) {observers.remove(observer);}public void notifyObservers() {for (Observer observer : observers) {observer.update();}}}```六、策略模式样板```public interface Strategy {public void algorithm();}public class ConcreteStrategyA implements Strategy { public void algorithm() {System.out.println("使用算法A");}}public class ConcreteStrategyB implements Strategy { public void algorithm() {System.out.println("使用算法B");}}public class Context {private Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy;}public void setStrategy(Strategy strategy) {this.strategy = strategy;}public void run() {strategy.algorithm();}}```以上就是几个常用的Java代码样板,这些样板代码不仅可以帮助开发人员提高开发效率,同时也提高了代码的可读性和可维护性。
优秀java开源项目代码

优秀java开源项目代码
有许多优秀的Java开源项目可供学习。
以下是一些示例:
1.Spring Framework:Spring是一个开源的Java平台,为开发者提供了
全面的编程和配置模型,以及一个轻量级的无侵入式框架。
它是一个为Java应用程序开发提供全面支持的框架,尤其在开发企业级应用程序方面表现突出。
2.Hibernate:Hibernate是一个对象关系映射(ORM)框架,它允许Java程
序员将对象模型映射到关系数据库中。
Hibernate提供了一种方式,使你可以直接将对象之间的相互作用映射到数据库的CRUD操作。
3.Apache Commons:Apache Commons是一组Java工具库,提供了许
多实用的功能,包括字符串操作、文件操作、数值计算等。
这个项目为Java开发者提供了许多易于使用且高效的工具。
4.Guava:Guava是Google的Java核心库,提供了很多有用的工具类和实
用程序,如缓存、并发库、原始类型支持、集合操作、字符串处理、I/O等。
flix Eureka:Eureka是一个服务发现组件,用于定位运行在AWS云
或其他云平台上的中间层服务,而不需要服务消费者知道服务提供者的实例ID。
flix Hystrix:Hystrix是一个容错管理工具,旨在隔离访问远程系统、
服务和第三方库的点,以防止级联故障。
flix Ribbon:Ribbon是一个客户端负载均衡器,有助于在云端实现
微服务之间的通信。
以上都是优秀的Java开源项目,你可以从中学习到很多知识和技巧。
20个java案例

20个java案例以下是20个Java案例,涵盖了不同的主题和功能。
每个案例都有一个简要的描述和示例代码。
1. 计算两个数的和。
描述,编写一个程序,计算两个整数的和并输出结果。
示例代码:java.int num1 = 10;int num2 = 5;int sum = num1 + num2;System.out.println("两个数的和为," + sum);2. 判断一个数是否为偶数。
描述,编写一个程序,判断一个整数是否为偶数,并输出结果。
示例代码:java.int num = 6;if (num % 2 == 0) {。
System.out.println(num + "是偶数。
");} else {。
System.out.println(num + "不是偶数。
");}。
3. 求一个数的阶乘。
描述,编写一个程序,计算一个正整数的阶乘,并输出结果。
示例代码:java.int num = 5;int factorial = 1;for (int i = 1; i <= num; i++) {。
factorial = i;}。
System.out.println(num + "的阶乘为," + factorial);4. 判断一个字符串是否为回文字符串。
描述,编写一个程序,判断一个字符串是否为回文字符串,并输出结果。
示例代码:java.String str = "level";boolean isPalindrome = true;for (int i = 0; i < str.length() / 2; i++) {。
if (str.charAt(i) != str.charAt(str.length() 1 i)) {。
isPalindrome = false;break;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一个Java小程序源代码(反转字符串)//BorderLayoutTest.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.event.*;public class test1{public static void main(String[] args){cloneFrame frame = new cloneFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.show();}}class cloneFrame extends JFrame{public cloneFrame(){setTitle("机试程序");setSize(600, 400);JPanel buttonPanel = new JPanel();buttonPanel.setBackground(new Color(56,43,85));Button1 = new JButton("点击复制反转字符串");Button1.addActionListener(new turnListener());buttonPanel.add(Button1);JPanel textPanel = new JPanel();textPanel.setBackground(new Color(100,100,100));field1 = new JTextField("姓名:老孙;学号:2004132028", 20);field2 = new JTextField("反转", 20);field2.setEditable(false);textPanel.add(field1);textPanel.add(field2);JPanel tuPanel = new JPanel();JLabel label = new JLabel(new ImageIcon("006.gif"));tuPanel.add(label);tuPanel.setBackground(new Color(100,100,100));Container contentPane = getContentPane();contentPane.add(buttonPanel, BorderLayout.SOUTH);contentPane.add(textPanel, BorderLayout.NORTH);contentPane.add(tuPanel, BorderLayout.CENTER);contentPane.setBackground(new Color(100,100,100)); }private class turnListenerimplements ActionListener{public void actionPerformed(ActionEvent event){String gets = field1.getText();int i = gets.length();StringBuffer buffer = new StringBuffer(i);for(int j=i-1;j>=0;j--){buffer.append(gets.charAt(j));}String gets2 = buffer.toString();field2.setText(gets2);}}Container contentPane = getContentPane();contentPane.add(buttonPanel, BorderLayout.SOUTH);contentPane.add(textPanel, BorderLayout.NORTH);contentPane.add(tuPanel, BorderLayout.CENTER);contentPane.setBackground(new Color(100,100,100)); }private class turnListenerimplements ActionListener{public void actionPerformed(ActionEvent event){String gets = field1.getText();int i = gets.length();StringBuffer buffer = new StringBuffer(i);for(int j=i-1;j>=0;j--){buffer.append(gets.charAt(j));}String gets2 = buffer.toString();field2.setText(gets2);}}private JButton Button1;private JTextField field1;private JTextField field2;}Java1package com.kenki.emp;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.SQLException;import java.sql.*;public class emp extends HttpServlet {private static final String CONTENT_TYPE = "text/html; charset=GBK";//Initialize global variablespublic void init() throws ServletException {}//Process the HTTP Get requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();String code = request.getParameter("code");String name = request.getParameter("name");String pay = request.getParameter("pay");System.out.println("empcode:" + code);System.out.println("name:" + name);System.out.println("pay:" + pay);//创建驱动new com.microsoft.jdbc.sqlserver.SQLServerDriver();String strd ="jdbc:microsoft:sqlserver://localhost:1433;databasename=emp_dates"; String username = "sa";String pws = "";try {java.sql.Connection conn = java.sql.DriverManager.getConnection( strd, username, pws);String strs = "insert into emp values(?,?,?)";java.sql.PreparedStatement pre = conn.prepareStatement(strs); pre.setString(1, code);pre.setString(2, name);pre.setString(3, pay);pre.execute();pre.close();conn.close();//重定向至查询页面out.println("成功保存!!");response.sendRedirect("emp.html");} catch (SQLException ss) {ss.printStackTrace();response.sendRedirect("/WebModule1/error.html");}}//Process the HTTP Post requestpublic void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {doGet(request, response);}//Clean up resourcespublic void destroy() {}Java2-聊天程序//这是个聊天程序,在ECLIPSE 运行Client.java 就可以了。
连接是:localhost//Server 代码,package message;import java.io.*;import .*;import java.util.*;public class Server {public static void main(String[] args) throws Exception{ System.out.print("Server");ServerSocket socket=new ServerSocket(8888);Vector v=new Vector();while(true){Socket sk=socket.accept();DataInputStream in=new DataInputStream(sk.getInputStream()); DataOutputStream out=new DataOutputStream(sk.getOutputStream()); v.add(sk);new ServerThread(in,v).start();}}}//ServerThread.java 代码package message;import .*;import java.io.*;import java.util.*;public class ServerThread extends Thread{DataInputStream in;Vector all;public ServerThread(DataInputStream in,Vector v){this.in=in;this.all=v;}public void run(){while(true){try{String s1=in.readUTF();for(int i=0;i<all.size();i++){Object obj=all.get(i);Socket socket=(Socket)obj; DataOutputStream out=new DataOutputStream(socket.getOutputStream()); out.writeUTF(s1);System.out.print(i);out.flush();}System.out.print("Message send over!");}catch(Exception e){e.printStackTrace();};}}}//ClientFrame.java 代码package message;import java.awt.*;import java.awt.event.*;import javax.swing.*;import .*;import java.io.*;public class ClientFrame extends JFrame implements ActionListener{JButton b1=new JButton ("SendMessage");JButton b2=new JButton("Link Server");JTextField t1=new JTextField(20);JTextField t2=new JTextField(20);JLabel l=new JLabel("输入服务器名字:");JTextArea area=new JTextArea(10,20);JPanel p1=new JPanel();JPanel p2=new JPanel();JPanel p3=new JPanel();JPanel p4=new JPanel();Socket socket;public ClientFrame(){this.getContentPane().add(p1);p2.add(new JScrollPane(area));p3.add(t1);p3.add(b1);p4.add(l);p4.add(t2);p4.add(b2);p2.setLayout(new FlowLayout()); p3.setLayout(new FlowLayout()); p4.setLayout(new FlowLayout()); p1.setLayout(new BorderLayout()); p1.add("North",p2);p1.add("Center",p3);p1.add("South",p4);b1.addActionListener(this);b2.addActionListener(this);this.pack();show();}Java3-猜数字游戏/*1、编写一个猜数字的游戏,由电脑随机产生一个100以内的整数,让用户去猜,如果用户猜的比电脑大,则输出“大了,再小点!”,反之则输出“小了,再大点!”,用户总共只能猜十次,并根据用户正确猜出答案所用的次数输出相应的信息,如:只用一次就猜对,输出“你是个天才!”,八次才猜对,输出“笨死了!”,如果十次还没有猜对,则游戏结束!*/import java.util.*;import java.io.*;public class CaiShu{public static void main(String[] args) throws IOException{Random a=new Random();int num=a.nextInt(100);System.out.println("请输入一个100以内的整数:");for (int i=0;i<=9;i++){BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));String str=bf.readLine();int shu=Integer.parseInt(str);if (shu>num)System.out.println("输入的数大了,输小点的!"); else if (shu<num)System.out.println("输入的数小了,输大点的!"); else {System.out.println("恭喜你,猜对了!");if (i<=2)System.out.println("你真是个天才!");else if (i<=6)System.out.println("还将就,你过关了!");else if (i<=8)System.out.println("但是你还……真笨!");elseSystem.out.println("你和猪没有两样了!");break;}}}}package GuessNumber;import java.io.*;import java.io.BufferedWriter;public class GuessNumber {public void show() {DataInputStream stdin = new DataInputStream(System.in); BufferedInputStream buffin = new BufferedInputStream(stdin); number = (int) (Math.random() * 10000);try {while (flag) {System.out.println("产生的随机数是:"+number);System.out.println("这是一个猜数字的小游戏,请您输入一个从0到10000的数字!");input = stdin.readLine();// guessnumber=Integer.parseInt(input);/** if(Character.isLetter(guessnumber)){* System.out.println("你输入的不是数字,请输入一个数字!"); flag=true; } *//** if(!Character.isDigit(input)){* System.out.println("你输入的不是数字,请输入一个数字!"); flag=true; } */guessnumber = Integer.parseInt(input);// guessnumber=Integer.valueOf(stdin.readLine()).intValue(); System.out.println("你输入的数是:" + guessnumber);{if (number < guessnumber)System.out.println("你输入的数大了请重新输入!");if (number > guessnumber)System.out.println("你输入的数小了请重新输入!");count++;flag = true;}if (number == guessnumber) {System.out.println("你真历害这么快你就猜对了!");System.out.println("你一共猜了" + count + "次");flag = false;System.out.println("请输入你的名字:");String name = stdin.readLine();byte names[] = name.getBytes("ISO-8859-1"); userName = new String(names);System.out.println("姓名:" + userName); System.out.println("记录是:" + count + "次"); SaveFile save = new SaveFile();save.output(userName, 0, userName.length());}// guessnumber=Integer.parseInt(stdin.readLine()); }stdin.close();buffin.close();} catch (IOException e) {e.getMessage();// e.toString();System.out.println("产生了异常!");}}public static void main(String[] args) { GuessNumber gus = new GuessNumber();gus.show();* try{ System.out.println("按回车结束....."); System.in.read(); } * catch(IOException e){}*/}private static String input; // 用户开始输入数字或字母private static int number; // 产生的随机数private static int guessnumber;// 用户输入的的数字private static int count = 0; // 用统计用户猜的次数private boolean flag = true; // 标记继续输入数字进行猜private String userName; // 用来记录猜对的用户名字}class SaveFile {// 这个方法是将传过来的名字写入文件里public void output(String name, int a, int length) {FileWriter sout = new FileWriter("Gamererecord.txt"); BufferedWriter out = new BufferedWriter(sout);sout.write(name, 0, length);sout.close();out.close();} catch (IOException e) {System.out.println("IO Error" + e);}}}可以直接出结果的,不过你得先建立一个名为GuessNumber的包,在此包下建立一个名为GuessNumber的类,然后将些段代码粘贴进来根据提示就可以出结果的JAVA小游戏代码int player1win,player2win;protected synchronized void keyPressed(int keyCode){...else if(action == Canvas.FIRE){if(chesses[selectedY][selectedX]==null){chesses[selectedY][selectedX]=new Chesses(this.isPlayer1); if(checkWin()){String winner;if(isPlayer1){winner="白方胜利";player1win++;}else{winner="红方胜利";player2win++;}try{Thread.sleep(3000);}catch(Exception e){}Alert winAlert=new Alert("",winner+"\n白方"+player1win+":"+player2win+"红方", null,);winAlert.setTimeout(Alert.FOREVER);Display.getDisplay(gobang).setCurrent(winAlert,this); init();repaint();}this.isPlayer=!this.isPlayer1;//切换下棋方}}repaint();}private boolean checkWin(){int num=1;if(num<5){num=1;for(int i=1;i<4;i++){if(isPlayer1(selectedX-i,selectedY)){num++;}ease break;}for(int i=1;i<4;i++){if(isPlayer1(selectedX+1,selectedY)){num++;}else break;}}if(num<5){num=1;for(int i=1;i<4;i++){if(isPlayer1(selectedX-i,selectedY)){ num++;}ease break;}for(int i=1;i<4;i++){if(isPlayer1(selectedX+1,selectedY)){ num++;}else break;}}if(num<5{num=1;for(int i=1;i<=4;i++){if(isPlayer1(sesectedX,selectedY-i)){ num++;}ease break;}for(int i=1;i<=4;i++){if(isPlayer1(selectedX.,selectedY+i)) num++;else break;}}if(num<5){num=1;for(int i=1;i<=4;i++){if(isPlayer1(selectedX+i,selectedY-i)) num++;else break;}for(int i=1;i<=4;i++){if(isPlayer1(selectedX-i,selectedY+i)) num++;else break;}}if(num>=5)return true;elsereturn false;}private boolean isPlayer1(int y,int x){if(x<=15 && x>=0 && y<=15 && y>=0 && chesses[x][y]!=null){ if(chesses[x][y].isPlayer1==this.isPlayer1)return true;elsereturn false;}else return fale;}JAVA计算器源代码import java.awt.*;import java.awt.event.*;import ng.*;import javax.swing.*;public class Counter extends Frame{//声明三个面板的布局GridLayout gl1,gl2,gl3;Panel p0,p1,p2,p3;JTextField tf1;TextField tf2;Buttonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b1 9,b20,b21,b22,b23,b24,b25,b26;StringBuffer str;//显示屏所显示的字符串double x,y;//x和y都是运算数int z;//Z表示单击了那一个运算符.0表示"+",1表示"-",2表示"*",3表示"/" static double m;//记忆的数字public Counter(){gl1=new GridLayout(1,4,10,0);//实例化三个面板的布局gl2=new GridLayout(4,1,0,15);gl3=new GridLayout(4,5,10,15);tf1=new JTextField(27);//显示屏tf1.setHorizontalAlignment(JTextField.RIGHT); tf1.setEnabled(false);tf1.setText("0");tf2=new TextField(10);//显示记忆的索引值tf2.setEditable(false);//实例化所有按钮、设置其前景色并注册监听器b0=new Button("Backspace");b0.setForeground(Color.red);b0.addActionListener(new Bt());b1=new Button("CE");b1.setForeground(Color.red);b1.addActionListener(new Bt());b2=new Button("C");b2.setForeground(Color.red);b2.addActionListener(new Bt());b3=new Button("MC");b3.setForeground(Color.red);b3.addActionListener(new Bt());b4=new Button("MR");b4.setForeground(Color.red);b4.addActionListener(new Bt());b5=new Button("MS");b5.setForeground(Color.red);b5.addActionListener(new Bt()); b6=new Button("M+");b6.setForeground(Color.red);b6.addActionListener(new Bt()); b7=new Button("7");b7.setForeground(Color.blue); b7.addActionListener(new Bt()); b8=new Button("8");b8.setForeground(Color.blue); b8.addActionListener(new Bt()); b9=new Button("9");b9.setForeground(Color.blue); b9.addActionListener(new Bt()); b10=new Button("/");b10.setForeground(Color.red); b10.addActionListener(new Bt()); b11=new Button("sqrt");b11.setForeground(Color.blue); b11.addActionListener(new Bt()); b12=new Button("4");b12.setForeground(Color.blue);b12.addActionListener(new Bt()); b13=new Button("5");b13.setForeground(Color.blue); b13.addActionListener(new Bt()); b14=new Button("6");b14.setForeground(Color.blue); b14.addActionListener(new Bt()); b15=new Button("*");b15.setForeground(Color.red); b15.addActionListener(new Bt()); b16=new Button("%");b16.setForeground(Color.blue); b16.addActionListener(new Bt()); b17=new Button("1");b17.setForeground(Color.blue); b17.addActionListener(new Bt()); b18=new Button("2");b18.setForeground(Color.blue); b18.addActionListener(new Bt()); b19=new Button("3");b19.setForeground(Color.blue); b19.addActionListener(new Bt());b20=new Button("-");b20.setForeground(Color.red); b20.addActionListener(new Bt()); b21=new Button("1/X");b21.setForeground(Color.blue); b21.addActionListener(new Bt()); b22=new Button("0");b22.setForeground(Color.blue); b22.addActionListener(new Bt()); b23=new Button("+/-");b23.setForeground(Color.blue); b23.addActionListener(new Bt()); b24=new Button(".");b24.setForeground(Color.blue); b24.addActionListener(new Bt()); b25=new Button("+");b25.setForeground(Color.red); b25.addActionListener(new Bt()); b26=new Button("=");b26.setForeground(Color.red); b26.addActionListener(new Bt());//实例化四个面板p0=new Panel();p1=new Panel();p2=new Panel();p3=new Panel();//创建一个空字符串缓冲区str=new StringBuffer();//添加面板p0中的组件和设置其在框架中的位置和大小p0.add(tf1);p0.setBounds(10,25,300,40);//添加面板p1中的组件和设置其在框架中的位置和大小p1.setLayout(gl1);p1.add(tf2);p1.add(b0);p1.add(b1);p1.add(b2);p1.setBounds(10,65,300,25);//添加面板p2中的组件并设置其的框架中的位置和大小p2.setLayout(gl2);p2.add(b3);p2.add(b5);p2.add(b6);p2.setBounds(10,110,40,150);//添加面板p3中的组件并设置其在框架中的位置和大小p3.setLayout(gl3);//设置p3的布局p3.add(b7);p3.add(b8);p3.add(b9);p3.add(b10);p3.add(b11);p3.add(b12);p3.add(b13);p3.add(b14);p3.add(b15);p3.add(b16);p3.add(b17);p3.add(b18);p3.add(b19);p3.add(b20);p3.add(b21);p3.add(b22);p3.add(b24);p3.add(b25);p3.add(b26);p3.setBounds(60,110,250,150);//设置框架中的布局为空布局并添加4个面板setLayout(null);add(p0);add(p1);add(p2);add(p3);setResizable(false);//禁止调整框架的大小//匿名类关闭窗口addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e1) {System.exit(0);}});setBackground(Color.lightGray); setBounds(100,100,320,280);setVisible(true);}//构造监听器class Bt implements ActionListener{public void actionPerformed(ActionEvent e2){try{if(e2.getSource()==b1)//选择"CE"清零{tf1.setText("0");//把显示屏清零str.setLength(0);//清空字符串缓冲区以准备接收新的输入运算数}else if(e2.getSource()==b2)//选择"C"清零{tf1.setText("0");//把显示屏清零str.setLength(0);}else if(e2.getSource()==b23)//单击"+/-"选择输入的运算数是正数还是负数{x=Double.parseDouble(tf1.getText().trim());tf1.setText(""+(-x));}else if(e2.getSource()==b25)//单击加号按钮获得x的值和z的值并清空y的值{x=Double.parseDouble(tf1.getText().trim());str.setLength(0);//清空缓冲区以便接收新的另一个运算数y=0d;z=0;}else if(e2.getSource()==b20)//单击减号按钮获得x的值和z的值并清空y的值{x=Double.parseDouble(tf1.getText().trim());str.setLength(0);y=0d;z=1;}else if(e2.getSource()==b15)//单击乘号按钮获得x的值和z的值并清空y的值{x=Double.parseDouble(tf1.getText().trim());str.setLength(0);y=0d;z=2;}else if(e2.getSource()==b10)//单击除号按钮获得x的值和z的值并空y的值{x=Double.parseDouble(tf1.getText().trim());str.setLength(0);y=0d;z=3;}else if(e2.getSource()==b26)//单击等号按钮输出计算结果{str.setLength(0);switch(z){case 0 : tf1.setText(""+(x+y));break;case 1 : tf1.setText(""+(x-y));break;case 2 : tf1.setText(""+(x*y));break;case 3 : tf1.setText(""+(x/y));break;}}else if(e2.getSource()==b24)//单击"."按钮输入小数{if(tf1.getText().trim().indexOf(′.′)!=-1)//判断字符串中是否已经包含了小数点{}else//如果没数点有小{if(tf1.getText().trim().equals("0"))//如果初时显示为0{str.setLength(0);tf1.setText((str.append("0"+e2.getActionCommand())).toString());}else if(tf1.getText().trim().equals(""))//如果初时显示为空则不做任何操作{}else{tf1.setText(str.append(e2.getActionCommand()).toString());}}y=0d;}else if(e2.getSource()==b11)//求平方根{x=Double.parseDouble(tf1.getText().trim()); tf1.setText("数字格式异常");if(x<0)tf1.setText("负数没有平方根");elsetf1.setText(""+Math.sqrt(x));str.setLength(0);y=0d;}else if(e2.getSource()==b16)//单击了"%"按钮{x=Double.parseDouble(tf1.getText().trim()); tf1.setText(""+(0.01*x));str.setLength(0);y=0d;}else if(e2.getSource()==b21)//单击了"1/X"按钮{x=Double.parseDouble(tf1.getText().trim()); if(x==0){tf1.setText("除数不能为零");}else{tf1.setText(""+(1/x));}str.setLength(0);y=0d;}else if(e2.getSource()==b3)//MC为清除内存{m=0d;tf2.setText("");str.setLength(0);}else if(e2.getSource()==b4)//MR为重新调用存储的数据{if(tf2.getText().trim()!="")//有记忆数字{tf1.setText(""+m);}}else if(e2.getSource()==b5)//MS为存储显示的数据{m=Double.parseDouble(tf1.getText().trim());tf2.setText("M");tf1.setText("0");str.setLength(0);}else if(e2.getSource()==b6)//M+为将显示的数字与已经存储的数据相加要查看新的数字单击MR{m=m+Double.parseDouble(tf1.getText().trim());}else//选择的是其他的按钮{if(e2.getSource()==b22)//如果选择的是"0"这个数字键{if(tf1.getText().trim().equals("0"))//如果显示屏显示的为零不做操作{}else{tf1.setText(str.append(e2.getActionCommand()).toString());y=Double.parseDouble(tf1.getText().trim());}}else if(e2.getSource()==b0)//选择的是“BackSpace”按钮{if(!tf1.getText().trim().equals("0"))//如果显示屏显示的不是零{if(str.length()!=1){tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能抛出字符串越界异常}else{tf1.setText("0");str.setLength(0);}}y=Double.parseDouble(tf1.getText().trim());}else//其他的数字键{tf1.setText(str.append(e2.getActionCommand()).toString()); y=Double.parseDouble(tf1.getText().trim());}}}catch(NumberFormatException e){tf1.setText("数字格式异常");}catch(StringIndexOutOfBoundsException e){tf1.setText("字符串索引越界");}}}public static void main(String args[]){new Counter();}}简洁java计算器代码import java.awt.*;import java.awt.event.*;import javax.swing.*; //引入所需要的包class MyFrame extends JFrame implements ActionListener{ private JButton b1,b2,b3,b4,b5,b6;private TextField t1,t2,t3; //定义六个按钮和三个文本域public MyFrame(String s){super(s);b1=new JButton("加");b2=new JButton("减");b3=new JButton("乘");b4=new JButton("除");//对按钮加文字标签Panel p=new Panel(); //生成一个面板p.setLayout(new FlowLayout()); //以FlowLayout来规划面板中的组件t1=new TextField ("",4);t2=new TextField("",4);t3=new TextField("",4); //生成文本域并设置长度p.add(new JLabel("Num1"));p.add(t1);p.add(new JLabel("Num2"));p.add(t2);p.add(new JLabel("Res"));p.add(t3);//顺次在面板中加入按钮和文本域t3.setEditable(false); //设置t3不可编辑Panel button=new Panel();button.setLayout(new GridLayout(2,2));//以两行2列来布局button面板中的各组件button.add(b1);button.add(b2);button.add(b3);button.add(b4);getContentPane().add(button,BorderLayout.SOUTH); getContentPane().add(p,BorderLayout.NORTH);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);//注册事件监听器}public void actionPerformed(ActionEvent e){ //实现接口方法double number1=Double.parseDouble(t1.getText());double number2=Double.parseDouble(t2.getText());//得到文本域中的数字字符串调用parseDouble()函数转化为数值型数字if(e.getSource()==b1){double result=number1+number2;t3.setText(String.valueOf(result));//实现+}if(e.getSource()==b2){double result=number1-number2;t3.setText(String.valueOf(result));//实现-}if(e.getSource()==b3){double result=number1*number2; //实现*t3.setText(String.valueOf(result));}if(e.getSource()==b4) //实现/{double result=number1/number2;t3.setText(String.valueOf(result));}}}public class Calculator{public static void main(String[] args){MyFrame frm=new MyFrame("Welcome to my calculator"); //设置标题frm.setSize(320,240); //设置大小frm. setVisible(true);//可见}}THANKS !!!致力为企业和个人提供合同协议,策划案计划书,学习课件等等打造全网一站式需求欢迎您的下载,资料仅供参考。