经典Java程序源代码
1.加法器(该java源文件的名称是)import .*;import .*;public class Adder implements ActionListener{JFrame AdderFrame;JTextField TOprand1;JTextField TOprand2;JLabel LAdd,LSum;JButton BAdd,BClear;JPanel JP1,JP2;public Adder(){AdderFrame=new JFrame("AdderFrame");TOprand1=new JTextField("");TOprand2=new JTextField("");LAdd=new JLabel("+");LSum=new JLabel("= ");BAdd=new JButton("Add");BClear=new JButton("Clear");JP1=new JPanel();JP2=new JPanel();(this);(new ActionListener(){public void actionPerformed(ActionEvent event) {("");("");("=");}});(JP1);(TOprand1);(LAdd);(TOprand2);(LSum);(JP2);(BAdd);(BClear);().setLayout(new BorderLayout()); ().add(JP1,;().add(JP2,;(new WindowAdapter(){public void windowClosing(WindowEvent event){(0);}});();(true);(false);(250,100);}public void actionPerformed(ActionEvent event){double sum=(double)()).doubleValue()+()).doubleValue());("="+sum);}public static void main(String[] args){Adder adder=new Adder();}}2.小型记事本(该java源文件由两个类构成,名称为)import .*;import .*;import .*;class mynotepad extends JFrame{File file=null;Color color=;mynotepad(){initTextContent();initMenu();initAboutDialog();}void initTextContent(){getContentPane().add(new JScrollPane(content)); }JTextPane content=new JTextPane();JFileChooser openfile=new JFileChooser();JColorChooser opencolor=new JColorChooser();JDialog about=new JDialog(this);JMenuBar menu=new JMenuBar();ength;j++){menus[i].add(optionofmenu[i][j]);optionofmenu[i][j].addActionListener( action );}}(menu);}ActionListener action=new ActionListener(){ quals(name)){("");file=null;}else if("打开".equals(name)){if(file !=null)(file);int returnVal=;if(returnVal=={file=();unfold();}}else if("保存".equals(name)){if(file!=null) (file);int returnVal=;if(returnVal=={file=();saving();}}else if("退出".equals(name)){mynotepad f=new mynotepad();int s=(f,"退出?","退出",; if(s==(0);}else if("剪切".equals(name)){();}else if("复制".equals(name)) {();}else if("粘贴".equals(name)) {();}else if("颜色".equals(name)) {color=,"",color);(color);}else if("关于".equals(name)){(300,150);();}}};void saving(){try{FileWriter Writef=new FileWriter(file);());();}catch(Exception e){();}}void unfold(){try{FileReader Readf=new FileReader(file);int len=(int)();char []buffer=new char[len];(buffer,0,len);();(new String(buffer));}catch(Exception e){();}}void initAboutDialog(){(new GridLayout(3,1));().setBackground;().add(new JLabel("我的记事本程序"));dd(new JLabel("制作者:Fwx"));().add(new JLabel("2007年12月"));(true); ;import .*;class simplecalculator{static String point=new String();static String Amal=new String();static String ONE=new String();static String TWO=new String();static String THREE=new String();static String FOUR=new String();static String FIVE=new String();static String SIX=new String();static String SEVEN=new String();static String EIGHT=new String();static String NINE=new String();static String ZERO=new String();static String ResultState=new String();static Double QF;static JButton zero=new JButton("0");static JButton one=new JButton("1"); static JButton two=new JButton("2"); static JButton three=new JButton("3"); static JButton four=new JButton("4"); static JButton five=new JButton("5"); static JButton six=new JButton("6"); static JButton seven=new JButton("7"); static JButton eight=new JButton("8"); static JButton nine=new JButton("9"); static JButton add=new JButton("+"); static JButton sub=new JButton("-"); static JButton mul=new JButton("*"); static JButton div=new JButton("/"); static JButton QuFan=new JButton("+/-"); static JButton Dian=new JButton("."); static JButton equal=new JButton("=");static JButton clear=new JButton("C");static JButton BaiFen=new JButton("%"); static JButton FenZhiYi=new JButton("1/x"); static int i=0;static Double addNumber;static Double subNumber;static Double mulNumber;static Double divNumber;static Double equalNumber;static Double temp;static JTextArea result=new JTextArea(1,20); public static void main(String[] args){JFrame frame=new JFrame("计算器"); (false);("");ResultState="窗口空";JPanel ForResult=new JPanel();JPanel ForButton7_clear=new JPanel(); JPanel ForButton4_mul=new JPanel(); JPanel ForButton1_sub=new JPanel(); JPanel ForButton0_equal=new JPanel();FlowLayout FLO=new FlowLayout(); (result);(FLO);(seven);(eight);(nine);(div);(clear);(FLO); (four); (five); (six); (mul); (BaiFen);(FLO); (one); (two); (three); (sub); (FenZhiYi);(FLO); (zero);(QuFan);(Dian);(add);(equal);().setLayout(FLO);().add(ForResult);().add(ForButton7_clear); ().add(ForButton4_mul); ().add(ForButton1_sub); ().add(ForButton0_equal);;(250,250,245,245); (false);(true);( new ActionListener(){public void actionPerformed(ActionEvent e) {("");ZERO="";ONE="";TWO="";THREE="";FOUR="";FIVE="";SIX="";SEVEN="";EIGHT="";NINE="";ResultState="窗口空";point="";i=0;}});( new ActionListener(){public void actionPerformed(ActionEvent e){ZERO="已经点击";ResultState="窗口不为空";if(ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FOUR=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"){("0");}if(ResultState=="窗口空"){("0");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){ONE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("1");}if(ResultState=="窗口空"){("1");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){TWO="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("2");}if(ResultState=="窗口空"){("2");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){THREE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0") {("3");}if(ResultState=="窗口空"){("3");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){FOUR="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("4");}if(ResultState=="窗口空"){("4");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){FIVE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("5");}if(ResultState=="窗口空"){("6");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){SIX="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("6");}if(ResultState=="窗口空"){("6");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){SEVEN="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("7");}if(ResultState=="窗口空"){("7");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){EIGHT="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("8");}if(ResultState=="窗口空"){("8");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){NINE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&()!="0"){("9");}if(ResultState=="窗口空"){("9");}}});( new ActionListener(){public void actionPerformed(ActionEvent e){point="已经点击";i=i+1;if(ResultState=="窗口不为空"&&i==1){(".");}}});( new ActionListener(){public void actionPerformed(ActionEvent e) {Amal="已经选择加号";addNumber=()).doubleValue();("");i=0;}});( new ActionListener(){public void actionPerformed(ActionEvent e) {Amal="已经选择减号";subNumber=()).doubleValue();("");i=0;}});( new ActionListener(){public void actionPerformed(ActionEvent e) {Amal="已经选择乘号";mulNumber=()).doubleValue();("");i=0;}});( new ActionListener(){public void actionPerformed(ActionEvent e){Amal="已经选择除号";divNumber=()).doubleValue();("");i=0;}});( new ActionListener(){public void actionPerformed(ActionEvent e) {QF=new Double()).doubleValue());QF=QF*(-1);());}});( new ActionListener(){public void actionPerformed(ActionEvent e) {equalNumber=()).doubleValue();if(Amal=="已经选择加号"){temp=addNumber+equalNumber;());}if(Amal=="已经选择减号"){temp=subNumber-equalNumber;());}if(Amal=="已经选择乘号"){temp=mulNumber*equalNumber;());}if(Amal=="已经选择除号"){temp=divNumber/equalNumber;());}}});( new ActionListener(){public void actionPerformed(ActionEvent e) {if(ResultState=="窗口不为空"){temp=()).doubleValue()/100;());}}});( new ActionListener(){public void actionPerformed(ActionEvent e) {temp=1/()).doubleValue());());}});}}3.图形化写字板(该java源文件的名称是);import .*;import .*;import class JNotePadUI extends JPanel{etSystemClipboard();String text = "";etPath();if (file == null){return;}etPath();if (savefile == null){return;}else{String docToSave = ();if (docToSave != null){FileOutputStream fstrm = null;BufferedOutputStream ostrm = null;try{fstrm = new FileOutputStream(savefile);ostrm = new BufferedOutputStream(fstrm);byte[] bytes = null;try{bytes = ();}catch (Exception e1){();}(bytes);}catch (IOException io){"IOException: "+ ());}finally{try{();();();}catch (IOException ioe){"IOException: "+ ());}}}}}else{return;}}}etVisible(true);(0);}dd(applet, ;(new appCloseL());(800, 500);(500,170);(true);();(false);}}4.数字化的连连看(该java源文件的名称是)import .*;import .*;importpublic class lianliankan implements ActionListener{JFrame mainFrame; ddActionListener(this);(diamondsButton[cols][rows]);}}exitButton=new JButton("退出"); (this);resetButton=new JButton("重列"); (this);newlyButton=new JButton("再来一局"); (this);(exitButton);(resetButton);(newlyButton);())));(fractionLable);(280,100,500,450);(true);}public void randomBuild(){int randoms,cols,rows;for(int twins=1;twins<=15;twins++){randoms=(int)()*25+1);for(int alike=1;alike<=2;alike++){cols=(int)()*6+1);rows=(int)()*5+1);while(grid[cols][rows]!=0){cols=(int)()*6+1);rows=(int)()*5+1);}[cols][rows]=randoms;}}}public void fraction(){())+100));}public void reload(){int save[] = new int[30];int n=0,cols,rows;int grid[][]= new int[8][7];for(int i=0;i<=6;i++){for(int j=0;j<=5;j++){if[i][j]!=0){save[n]=[i][j];n++;}}}n=n-1;=grid;while(n>=0){cols=(int)()*6+1);rows=(int)()*5+1);while(grid[cols][rows]!=0){cols=(int)()*6+1);rows=(int)()*5+1);}[cols][rows]=save[n];n--;}(false);pressInformation=false; etVisible(false);}}}public void estimateEven(int placeX,int placeY,JButton bz) {if(pressInformation==false){x=placeX;y=placeY;secondMsg=grid[x][y];secondButton=bz;pressInformation=true;}else{x0=x;y0=y;fristMsg=secondMsg;firstButton=secondButton;x=placeX;y=placeY;secondMsg=grid[x][y];secondButton=bz;if(fristMsg==secondMsg && secondButton!=firstButton) {。
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)中,访问速度较慢。
程序源代码模板 (2).doc
页面布局模块程序代码MainActivity.javapackage com.my.llkangame;//第一个页面import android.app.ListActivity;import android.app.ProgressDialog;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import com.plter.lib.android.java.controls.ArrayAdapter;import com.plter.linkgame.R;public class MainActivity extends ListActivity {private ArrayAdapter<GameListCellData> adapter;//定义适配器private ProgressDialog dialog=null;//dialog//savedInstanceStateprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main_activity);//main_activity.xml//设置适配器adapter=newArrayAdapter<MainActivity.GameListCellData>(this,yout.game_list_cell) {@Overridepublic void initListCell(int position, View listCell, ViewGroup parent) {ImageView iconIv = (ImageView) listCell.findViewById(R.id.iconIv);TextView labelTv=(TextView) listCell.findViewById(belTv);GameListCellData data = getItem(position);iconIv.setImageResource(data.iconResId);labelTv.setText(bel);}};setListAdapter(adapter);//适配器集合adapter.add(new GameListCellData("水果连连看", R.drawable.sg_icon, "sg_config.json"));adapter.add(new GameListCellData("蔬菜连连看", R.drawable.sc_icon, "sc_config.json"));adapter.add(new GameListCellData("动物连连看", R.drawable.dw_icon, "dw_config.json"));adapter.add(new GameListCellData("爱心连连看", R.drawable.love_icon, "love_config.json"));adapter.add(new GameListCellData("宝石连连看", R.drawable.coin_icon, "coin_config.json"));}@Overrideprotected void onPause() {if (dialog!=null) {dialog.dismiss();dialog=null;}super.onPause();}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {dialog=ProgressDialog.show(this, "请稍候", "正在加载游戏资源");GameListCellData data = adapter.getItem(position);Intent i = new Intent(this, LinkGameActivity.class);i.putExtra("configFile", data.gameConfigFile);startActivity(i);super.onListItemClick(l, v, position, id);}public static class GameListCellData{public String label=null;public int iconResId=0;public String gameConfigFile=null;public GameListCellData(String label,int iconResId,String gameConfigFile) {bel=label;this.iconResId=iconResId;this.gameConfigFile=gameConfigFile;}}}LinkGameActivity.javapackage com.my.llkangame;import android.app.Activity;import android.os.Bundle;import android.text.TextUtils;import android.view.Display;import android.widget.Button;import android.widget.TextView;import com.my.cord.Config;import com.my.cord.GameViewhhxx;import com.my.reader.InnerGameReader;import com.plter.linkgame.R;//游戏开始界面宽高、布局等且开始游戏public class LinkGameActivity extends Activity {private GameViewhhxx gameView;/** Called when the activity is first created. */@SuppressWarnings("deprecation")public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);String configFile = getIntent().getStringExtra("configFile");if (TextUtils.isEmpty(configFile)) {finish();return;}//获得屏幕宽高Display display = getWindowManager().getDefaultDisplay();Config.setScreenWidth(display.getWidth());Config.setScreenHeight(display.getHeight());//设置内容布局setContentView(yout.link_game_activity);gameView=(GameViewhhxx) findViewById(R.id.gameView);gameView.setTimeTv((TextView) findViewById(R.id.timeTv));gameView.setLevelTv((TextView) findViewById(R.id.levelTv));gameView.setBreakCardsBtn((Button) findViewById(R.id.breakCardsBtn));gameView.setNoteBtn((Button) findViewById(R.id.noteBtn));gameView.setPauseBtn((Button) findViewById(R.id.pauseBtn));//根据游戏资源包初始化游戏gameView.initWithGamePkg(InnerGameReader.readGame(this, configFile));//开始启动游戏gameView.showStartGameAlert();}protected void onPause() {gameView.pause();super.onPause();}protected void onResume() {gameView.resume();super.onResume();}}LinesContainer.javapackage com.my.cord;import java.util.List;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Path;import android.graphics.PointF;import android.view.View;import android.view.animation.AlphaAnimation;import android.view.animation.Animation;import android.view.animation.Animation.AnimationListener;/*** 设置对图片进行连接的线的宽度和颜色*/public class LinesContainer extends View implements AnimationListener{ private List<PointF> points=null;private final Paint paint=new Paint();private final Path path = new Path();private final AlphaAnimation aa = new AlphaAnimation(1, 0);public LinesContainer(Context context) {super(context);paint.setStyle(Style.STROKE);paint.setStrokeWidth(5);paint.setColor(0xFFFF0000);aa.setDuration(500);aa.setAnimationListener(this);setVisibility(View.GONE);}public void showLines(List<PointF> points){if (points.size()<2) {throw new RuntimeException("点的个数不能小于2");}else{setVisibility(View.VISIBLE);this.points=points;invalidate();startAnimation(aa);}}protected void onDraw(Canvas canvas) {if (points==null||points.size()<2) {return;}path.reset();PointF p=points.get(0);path.moveTo(p.x, p.y);for (int i = 1; i < points.size(); i++) {p=points.get(i);path.lineTo(p.x, p.y);}canvas.drawPath(path, paint);super.onDraw(canvas);}public void onAnimationStart(Animation animation) {}public void onAnimationEnd(Animation animation) { setVisibility(View.GONE);}public void onAnimationRepeat(Animation animation) {} }Config.javapackage com.my.cord;public class Config {private static float cardWidth=0;private static float cardHeight=0;private static float screenWidth=0;private static float screenHeight=0;private static float cardsOffsetX=0;private static float cardsOffsetY=0;/*** 游戏区域的宽度*/private static float gameCardsAreaWidth=0;/*** 游戏区域的高度*/private static float gameCardsAreaHeight=0;/*** 卡片的上边距*/public static final float GAME_CARDS_AREA_TOP=80;/*** 卡片的下边距*/public static final float GAME_CARDS_AREA_BOTTOM=80;/*** 卡片区域左边距*/public static final float GAME_CARDS_AREA_LEFT=0;/*** 卡片区域右边距*/public static final float GAME_CARDS_AREA_RIGHT=0;/*** @return the screenWidth*/public static float getScreenWidth() {return screenWidth;}/*** @param screenWidth the screenWidth to set*/public static void setScreenWidth(float screenWidth) {Config.screenWidth = screenWidth;Config.setGameCardsAreaWidth(Config.getScreenWidth()-Config.GAME_CARDS_AREA_ LEFT-Config.GAME_CARDS_AREA_RIGHT);computeCardWidthAndHeight();}/*** @return the screenHeight*/public static float getScreenHeight() {return screenHeight;}/*** @param screenHeight the screenHeight to set*/public static void setScreenHeight(float screenHeight) {Config.screenHeight = screenHeight;Config.setGameCardsAreaHeight(Config.getScreenHeight()-Config.GAME_CARDS_ARE A_BOTTOM-Config.GAME_CARDS_AREA_TOP);computeCardWidthAndHeight();}private static void computeCardWidthAndHeight(){float cardWidth=Config.getGameCardsAreaWidth()/Level.MAX_H_CARDS_COUNT;floatcardHeight=Config.getGameCardsAreaHeight()/Level.MAX_V_CARDS_COUNT;float min = Math.min(cardWidth, cardHeight);Config.setCardWidth(min);//卡片最小宽Config.setCardHeight(min);//卡片最小高}/*** @return the cardWidth*/public static float getCardWidth() {return cardWidth;}/*** @param cardWidth the cardWidth to set*/private static void setCardWidth(float cardWidth) {Config.cardWidth = cardWidth;}/*** @return the cardHeight*/public static float getCardHeight() {return cardHeight;}/*** @param cardHeight the cardHeight to set*/private static void setCardHeight(float cardHeight) {Config.cardHeight = cardHeight;}/*** @return the cardsOffsetX*/public static float getCardsOffsetX() {return cardsOffsetX;}/*** @param cardsOffsetX the cardsOffsetX to set*/public static void setCardsOffsetX(float cardsOffsetX) { Config.cardsOffsetX = cardsOffsetX;}/*** @return the cardsOffsetY*/public static float getCardsOffsetY() {return cardsOffsetY;}/*** @param cardsOffsetY the cardsOffsetY to set*/public static void setCardsOffsetY(float cardsOffsetY) { Config.cardsOffsetY = cardsOffsetY;}/*** @return the gameCardsAreaWidth*/public static float getGameCardsAreaWidth() {return gameCardsAreaWidth;}/*** @param gameCardsAreaWidth the gameCardsAreaWidth to set */private static void setGameCardsAreaWidth(float gameCardsAreaWidth) { Config.gameCardsAreaWidth = gameCardsAreaWidth;}/*** @return the gameCardsAreaHeight*/public static float getGameCardsAreaHeight() {return gameCardsAreaHeight;}/*** @param gameCardsAreaHeight the gameCardsAreaHeight to set*/private static void setGameCardsAreaHeight(float gameCardsAreaHeight) { Config.gameCardsAreaHeight = gameCardsAreaHeight;}}Picture.javapackage com.my.reader;import android.graphics.Bitmap;/*** Bitmap 面板**/public class Picture {public Picture(Bitmap bitmap) {this.bitmap=bitmap;id=__getId();}public Bitmap getBitmap() {return bitmap;}private int id=0;public int getId() {return id;}private Bitmap bitmap=null;private static int __id=0;private static int __getId(){__id++;return __id;}}算法分析模块程序代码Cardmm.javapackage com.my.cord;/**重排:先遍历当前页面还有的图片,调用随机算法调换页面中图片的位置* 先选中一张图片,获取此图片在垂直和水平方向上的的位置,判断是否被选中,判断当前已选中的图片个数*若选中图片个数小于2张,再选择一张图片,重复上一个动作,若选中图片个数达到2张,判断是否满足消除条件*若满足,则消除,若不满足,则不发生任何变化。
优秀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;}。
java项目代码
Java项目代码一、什么是Java项目代码Java项目代码是使用Java编程语言编写的程序源代码,用于创建、实现和管理Java应用程序。
Java是一种面向对象的编程语言,它的代码是通过编写类、方法和变量来组织的。
Java项目代码可以用于开发各种类型的应用程序,包括桌面应用程序、Web应用程序、移动应用程序等。
二、Java项目代码的特点Java项目代码具有以下几个特点:1. 可移植性Java是一种跨平台的编程语言,可以在不同的操作系统和硬件平台上运行。
这意味着通过编写一次Java项目代码,可以在多个平台上部署和运行应用程序,而无需针对不同平台编写不同的代码。
2. 面向对象Java是一种面向对象的编程语言,它支持面向对象的编程范式,包括封装、继承和多态等特性。
这使得Java项目代码更易于理解、维护和扩展。
3. 垃圾回收Java项目代码使用垃圾回收机制来自动管理内存。
在Java中,不需要手动分配和释放内存,虚拟机会自动检测和回收不再使用的对象,从而减少程序员的工作量和错误。
4. 强类型Java是一种强类型的编程语言,它要求变量在使用之前必须声明其类型,并且不允许隐式类型转换。
这种严格的类型检查提高了代码的可读性和可靠性。
5. 多线程支持Java项目代码可以利用Java提供的多线程机制实现并发处理。
多线程可以使应用程序同时执行多个任务,提高程序的运行效率和响应性。
三、如何编写Java项目代码要编写Java项目代码,需要遵循以下几个步骤:1. 确定项目需求在编写Java项目代码之前,需要明确项目的需求和目标。
这包括确定项目的功能和特性,以及所用到的技术和工具。
2. 设计项目架构在开始编写代码之前,需要进行项目架构的设计。
这包括确定项目的模块和组件,设计类的结构和关系,以及确定数据流和业务逻辑。
3. 编写代码根据项目的需求和架构设计,编写Java项目代码。
在编写代码时,需要遵循代码规范和最佳实践,使代码具有良好的可读性和可维护性。
JAVA小程序—贪吃蛇源代码
JAVA贪吃蛇源代码SnakeGame。
javapackage SnakeGame;import javax.swing。
*;public class SnakeGame{public static void main( String[]args ){JDialog。
setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java。
awt.*;import java。
util。
*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this。
add( new Point( 3, 3 ));this。
add(new Point(4, 3 ));this.add( new Point(5,3 ) );this。
add( new Point(6,3 ) );this。
add(new Point(7,3 ));this。
add( new Point( 8,3 ) );this。
add( new Point( 9, 3 ));this。
add( new Point( 10,3 ));}public void changeDirection( Point temp, int direction ) {this。
snakeDirection = direction;switch(direction ){case 1://upthis.snakeReDirection = 3;this。
add( new Point(temp.x,temp.y - 1 ));break;case 2://rightthis。
计算机程序源代码
import javax.swing.*;import java.awt.*;import javax.swing.border.*;import java.awt.event.*;public class SX7{JTextField field;JFrame f;JButton b;JLabel label;JPanel p1;JButton bb1,bb2,bb3;ActionListener h;Color cor1,cor2;Container con;GridBagLayout g;GridBagConstraints c;int gridx,gridy,gridwidth,gridheight,anchor,fill,ipadx,ipady;double weightx,weighty;Insets inset;Font t;boolean k1,/*控制字符的连续输出*/z,/*实现除零对其它按键的控制*/mh=true;/*保存控制显示*/ String op1,op2,r,ch,tf,str7,str11;Double r1,n1,n2,a,str8,str9,str10;int k,/*控制运算*/counter1,/*控制操作符*/counter2;/*控制连续运算*/SX7(){try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}makeJFrame();//添加JFrameaddmakeBarMenu();//添加菜单栏addButton();//添加组件f.setVisible(true);}private void addButton(){JPanel p=new JPanel();p1=new JPanel();p.setLayout(new GridLayout(1,4,3,6));p1.setLayout(new GridLayout(4,6,3,6));g=new GridBagLayout();con.setLayout(g);anchor=GridBagConstraints.CENTER;//当组件小于其显示区域时使用此字段。
Java 小程序连连看源代码
public void reload() {
int save[] = new int[30];
int n=0,cols,rows;
int grid[][]= new int[8][7];
for(int i=0;i<=6;i++) {
for(int j=0;j<=5;j++) {
resetButton.addActionListener(this);
newlyButton=new JButton("再来一局");
newlyButton.addActionListener(this);
southPanel.add(exitButton);
southPanel.add(resetButton);
thisContainer.add(southPanel,"South");
thisContainer.add(northPanel,"North");
centerPanel.setLayout(new GridLayout(6,5));
for(int cols = 0;cols < 6;cols++){
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
java程序积木源代码
旋转流程控制
加速下降流程控制
开始流程控制(Timer)
暂停流程控制
继续流程控制
结束流程控制
修改键盘事件
修改paintScore方法
Person I;
Person you;
I.love(you);
4 严格测试结果! TestCase
1) 如果"能够下落", 就下落一步
2) 否则就"着陆到墙里面"
3) 着落以后, "销毁充满的行", 并且记分
4) "检查游戏结束"了吗?
左右移动流程控制
分数计算
界面的绘制
键盘事件控制
就会固定在该处,而新的方块出现在区域上方开始落下。
(3)当区域中某一列横向格子全部由方块填满,则该行会消失
并成为玩家的得分。同时删除的行数越多,得分指数上升。
(4)当固定的方块堆到区域最上方而无法消除层数时,
则游戏结束。
(6)一般来说,游戏还会提示下一个要落下的方块,
熟练的玩家会计算到下一个方块,评估要如何进行。
由于游戏能不断进行下去对商业用游戏不太理想,
所以一般还会随着游戏的进行而加速提高难度。
(7)预先设置的随机发生器不断地输出单个方块到场地顶部
2 业务分析
找到有哪些业务对象根据图片的分析
tetris(俄罗斯方块)
|-- score 累计分数
|-- lines 销毁的行数
|-- 4 cell
3 数据模型, 一切业务对象转换为数字表示
场地按照行列划分为 20×10格子
格子有属性row, col, color
JAVA语言程序设计清华大学出版社书上例题源代码第二章
【2_1】//计算二个数的和class Example2_1 {public static void main(String args[]) {int x,y,s;x = 3;y = 5;s =x+y; //求和System.out.println("二数之和为:" + s);}}【2_2】//计算圆的面积class Example2_2 {public static void main(String args[]) {double pi,r,s;r = 10.8; //圆的半径pi = 3.1416;s = pi * r * r; //计算面积System.out.println("圆的面积为:" + s);}}【2_3】/* char 变量的用法*/class Example2_3 {public static void main(String args[]) {char ch1,ch2;ch1 = 88; // code for Xch2 = 'Y';System.out.print("ch1 and ch2:");System.out.println(ch1 + " " + ch2);}}【2_4】/* 布尔类型的用法*/class Example2_4 {public static void main(String args[]) {boolean b;b = false;System.out.println("b is " + b);b = true;System.out.println("b is " + b);// outcome of a relational operator is a boolean valueSystem.out.println("10 > 9 is " + (10 > 9));}}【2_5】public class Example2_5{public static void main(String[] agrs){//定义几个变量并赋值int a=41;int b=21;double x=6.4;double y=3.22;System.out.println("变量数值:");System.out.println("a="+a);System.out.println("b="+b);System.out.println("x="+x);System.out.println("y="+y);//加法System.out.println("加:");System.out.println("a+b="+(a+b));System.out.println("x+y="+(x+y));//减法System.out.println("减:");System.out.println("a-b="+(a-b));System.out.println("x-y="+(x-y));//乘法System.out.println("乘:");System.out.println("a*b="+(a*b));System.out.println("x*y="+(x*y));//除法System.out.println("除:");System.out.println("a/b="+(a/b));System.out.println("x/y="+(x/y));//从除法中求得余数System.out.println("计算余数:");System.out.println("a%b="+(a%b));System.out.println("x%y="+(x%y));//混合类型System.out.println("混合类型:");System.out.println("b+y="+(b+y));System.out.println("a*x="+(a*x));}}public class Example2_6{public static void main(String[] args){//定义若干整型数int i=37;int j=42;int k=42;System.out.println("变量数值");System.out.println("i="+i);System.out.println("j="+j);System.out.println("k="+k);//大于System.out.println("大于:");System.out.println("i>j="+(i>j));//falseSystem.out.println("j>i="+(j>i));//trueSystem.out.println("k>j="+(k>j));//false//大于等于System.out.println("大于等于:");System.out.println("i>=j="+(i>=j));//falseSystem.out.println("j>=i="+(j>=i));//trueSystem.out.println("k>=j="+(k>=j));//true//小于System.out.println("小于:");System.out.println("i<j="+(i<j));//trueSystem.out.println("j<i="+(j<i));//falseSystem.out.println("k<j="+(k<j));//false//小于等于System.out.println("小于等于:");System.out.println("i<=j="+(i<=j));//trueSystem.out.println("j<=i="+(j<=i));//falseSystem.out.println("k<=j="+(k<=j));//false//等于System.out.println("等于:");System.out.println("i==j="+(i==j));//falseSystem.out.println("k==j="+(k==j));//true//不等于System.out.println("不等于:");System.out.println("i!=j="+(i!=j));//trueSystem.out.println("k!=j="+(k!=j));//false}}class Example2_7{public static void main(String args[]){//字符char a1='银',a2='行',a3='帐',a4='号';//密鈅char secret='x';//异或运算加密a1=(char)(a1^secret); a2=(char)(a2^secret);a3=(char)(a3^secret); a4=(char)(a4^secret);System.out.println("密文:"+a1+a2+a3+a4);//再一次异或运算解密a1=(char)(a1^secret); a2=(char)(a2^secret);a3=(char)(a3^secret); a4=(char)(a4^secret);System.out.println("原文:"+a1+a2+a3+a4);}}【2_8】/* if结构*/public class Example2_8{public static void main(String args[]){int a=9,b=5,c=7,t;if(a>b){t=a; a=b; b=t;}if(a>c){t=a; a=c; c=t;}if(b>c){t=b; b=c; c=t;}System.out.println("a="+a+",b="+b+",c="+c);}}/* if-else-if 结构. */class Example2_9 {public static void main(String args[]) {int month = 4; // 4月份String season;if(month == 12 || month == 1 || month == 2){season = "冬天";}else if(month == 3 || month == 4 || month == 5){season = "春天"; }else if(month == 6 || month == 7 || month == 8){season = "夏天"; }else if(month == 9 || month == 10 || month == 11){season = "秋天"; }else{ season = "不合法的月份"; }System.out.println("4月是" + season + ".");}}【2_10】/* switch开关语句*/import java.applet.*;import java.awt.*;public class Example2_10 extends Applet{public void paint(Graphics g){int x=1,y=1;switch(x+y){case 1 :g.setColor(Color.red);g.drawString("i am 1",5,10);break;case 2:g.setColor(Color.blue);g.drawString("i am 2",5,10);// break;case 3:g.setColor(Color.green);g.drawString("i am 3",5,10);break;default:g.drawString("没有般配的",5,10);}}/*<APPLET CODE="Example2_10.class" WIDTH="200" HEIGHT="300"></APPLET>*/【2_11】/* for循环*/import javax.swing.JOptionPane;public class Example2_11{public static void main(String[] args){ int sum=0;for(int i=1;i<=100;i++){sum=sum+i;}JOptionPane.showMessageDialog(null,"1+2+3+...+100= "+sum);System.exit(0); //退出程序}}【2_12】/* while循环*/import javax.swing.JOptionPane;public class Example2_12{public static void main(String[] args){int s=1, i=1;while(i<=10){s=s*i;i++;}JOptionPane.showMessageDialog(null,"1*2*3*...*10= "+s);System.exit(0); //退出程序}}/* do-while循环*/import java.applet.*;import java.awt.*;public class Example2_13 extends Applet{public void paint(Graphics g){int i=1;do{g.drawOval(110-i*10,110-i*10,i*20,i*20);i++;}while(i<=10);}}/*<APPLET CODE="Example2_13.class" WIDTH="300" HEIGHT="300"></APPLET>*/【2_14】/* 使用break语句跳出循环 */import javax.swing.JOptionPane;class Example2_14{public static void main(String args[]){for(int i=0; i<100; i++){if(i == 10) break; // i=10时跳出循环JOptionPane.showMessageDialog(null,"i="+i);}JOptionPane.showMessageDialog(null,"循环已经结束!");System.exit(0); //退出程序}}/* 使用break语句跳出内循环 */class Example2_15{public static void main(String args[]){for(int i=1; i<6; i++){for(int j=1;j<3; j++){if(i == 3) break; // i=5时跳出循环int sum=i+j;System.out.println(i+"+"+j+"="+sum);}}System.out.println("循环已经结束!");}}【2_16】/* 使用"标签化中断"的break语句跳出循环 */class Example2_16{public static void main(String args[]){out: for(int i=1; i<6; i++) //设置标号{for(int j=1;j<3; j++){if(i == 3) break out; // i=3时跳出循环int sum=i+j;System.out.println(i+"+"+j+"="+sum);}}System.out.println("循环已经结束!");}}【2_17】/*continue语句打印三角形*/import javax.swing.JOptionPane;class Example2_17 {public static void main(String args[]) {String output="";for(int i=0; i<5; i++) {for(int j=0; j<5; j++) {if(j > i) {continue ;}output= output +"*"+" ";}output=output+"\n";}JOptionPane.showMessageDialog(null,output);System.exit(0);}}【2_18】/* 求一组数字的平均值*/import javax.swing.JOptionPane;class Example2_18 {public static void main(String args[]) {double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};double result = 0;for(int i=0; i<5; i++){result = result + nums[i]; }JOptionPane.showMessageDialog(null,"平均值为:" + result / 5);System.exit(0);}}【2_19】// 二维数组赋值class Example2_19{public static void main(String args[]) {int twoD[][]= new int[4][5];int i, j, k = 0;for(i=0; i<4; i++)for(j=0; j<5; j++) {twoD[i][j] = k;k++;}for(i=0; i<4; i++) {for(j=0; j<5; j++)System.out.print(twoD[i][j] + " ");System.out.println();}}}【2_20】import java.util.*;class Example2_20{public static void main(String[] args){Vector v1 =new Vector();for (int i=1;i<10;i++){v1.addElement(" " + i);System.out.println(v1.toString());}v1.insertElementAt("abc",5);System.out.println("\n插入元素:"+v1.toString());}}【2_21】import java.util.*;public class Example2_21{ public static void main(String args[]){ String s="boy,java,Applet girl,Hat";StringTokenizer st=new StringTokenizer(s," ,"); //空格和逗号做分int number=st.countTokens();while(st.hasMoreTokens()){ String str=st.nextToken();System.out.println(str);}System.out.println("s共有单词:"+number+"个");}}。
