import java.awt.BorderLayout;
創(chuàng)新互聯(lián)是一家專(zhuān)注于成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),阜寧網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:阜寧等地區(qū)。阜寧做網(wǎng)站價(jià)格咨詢(xún):13518219792
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class MainClass extends JFrame {
ControlSnake control;
Toolkit kit;
Dimension dimen;
public static void main(String[] args) {
new MainClass("my snake");
}
public MainClass(String s) {
super(s);
control = new ControlSnake();
control.setFocusable(true);
kit = Toolkit.getDefaultToolkit();
dimen = kit.getScreenSize();
add(control);
setLayout(new BorderLayout());
setLocation(dimen.width / 3, dimen.height / 3);// dimen.width/3,dimen.height/3
setSize(FWIDTH, FHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public static final int FWIDTH = 315;
public static final int FHEIGHT = 380;
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class ControlSnake extends JPanel implements ActionListener {
Random rand;
ArrayListPoint list, listBody;
String str, str1;
static boolean key;
int x, y, dx, dy, fx, fy, flag;
int snakeBody;
int speed;
public ControlSnake() {
snakeBody = 1;
str = "上下左右方向鍵控制 P鍵暫停...";
str1 = "現(xiàn)在的長(zhǎng)度為:" + snakeBody;
key = true;
flag = 1;
speed = 700;
rand = new Random();
list = new ArrayListPoint();
listBody = new ArrayListPoint();
x = 5;
y = 5;
list.add(new Point(x, y));
listBody.add(list.get(0));
dx = 10;
dy = 0;
fx = rand.nextInt(30) * 10 + 5;// 2
fy = rand.nextInt(30) * 10 + 5;// 2
setBackground(Color.BLACK);
setSize(new Dimension(318, 380));
final Timer time = new Timer(speed, this);
time.start();
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37) {
dx = -10;
dy = 0;
} else if (e.getKeyCode() == 38) {
dx = 0;
dy = -10;
} else if (e.getKeyCode() == 39) {
dx = 10;
dy = 0;
} else if (e.getKeyCode() == 40) {
dx = 0;
dy = 10;
} else if (e.getKeyCode() == 80) {
if (flag % 2 == 1) {
time.stop();
}
if (flag % 2 == 0) {
time.start();
}
flag++;
}
}
});
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 400, 400);
g.setColor(Color.DARK_GRAY);
g.drawLine(3, 3, 305, 3);
g.drawLine(3, 3, 3, 305);
g.drawLine(305, 3, 305, 305);
g.drawLine(3, 305, 305, 305);
g.setColor(Color.PINK);
for (int i = 0; i listBody.size(); i++) {
g.fillRect(listBody.get(i).x, listBody.get(i).y, 9, 9);
}
g.fillRect(x, y, 9, 9);
g.setColor(Color.ORANGE);
g.fillRect(fx, fy, 9, 9);
g.setColor(Color.DARK_GRAY);
str1 = "現(xiàn)在的長(zhǎng)度為:" + snakeBody;
g.drawString(str, 10, 320);
g.drawString(str1, 10, 335);
}
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
if (makeOut() == false) {
JOptionPane.showMessageDialog(null, "重新開(kāi)始......");
speed = 700;
snakeBody = 1;
x = 5;
y = 5;
list.clear();
list.add(new Point(x, y));
listBody.clear();
listBody.add(list.get(0));
dx = 10;
dy = 0;
}
addPoint(x, y);
if (x == fx y == fy) {
speed = (int) (speed * 0.8);//速度增加參數(shù)
if (speed 200) {
speed = 100;
}
fx = rand.nextInt(30) * 10 + 5;// 2
fy = rand.nextInt(30) * 10 + 5;// 2
snakeBody++;// 2
} // 2
repaint();
}
public void addPoint(int xx, int yy) {
// 動(dòng)態(tài)的記錄最新發(fā)生的50步以?xún)?nèi)的移動(dòng)過(guò)的坐標(biāo)
// 并畫(huà)出最新的snakeBody
if (list.size() 100) {//蛇身長(zhǎng)度最長(zhǎng)為100
list.add(new Point(xx, yy));
} else {
list.remove(0);
list.add(new Point(xx, yy));
}
if (snakeBody == 1) {
listBody.remove(0);
listBody.add(0, list.get(list.size() - 1));
} else {
listBody.clear();
if (list.size() snakeBody) {
for (int i = list.size() - 1; i 0; i--) {
listBody.add(list.get(i));
}
} else {
for (int i = list.size() - 1; listBody.size() snakeBody; i--) {
listBody.add(list.get(i));
}
}
}
}
public boolean makeOut() {
if ((x 3 || y 3) || (x 305 || y 305)) {
return false;
}
for (int i = 0; i listBody.size() - 1; i++) {
for (int j = i + 1; j listBody.size(); j++) {
if (listBody.get(i).equals(listBody.get(j))) {
return false;
}
}
}
return true;
}
}
/*貪吃蛇代碼*/
第一題: 元素的復(fù)制
import?java.util.Arrays;
public?class?ArrayDemo?{
public?static?void?main(String[]?args)?{
int[]?scores?=?{91,85,98,62,78,93};
int[]?newScores=Arrays.copyOfRange(scores,?0,?5);//復(fù)制元素,?左開(kāi)右閉區(qū)間[0,5)
System.out.println(Arrays.toString(newScores));//調(diào)用數(shù)組工具類(lèi)的方法轉(zhuǎn)成字符串并打印
}
}
第二題: 這題雖然使用集合更方便 , 但卻是非常好的一維數(shù)組的訓(xùn)練題目.
解法一: 集合解決 隨機(jī)產(chǎn)生7個(gè)不重復(fù)的數(shù)字很簡(jiǎn)單
import?java.util.HashSet;
import?java.util.Random;
public?class?NumberTest?{
public?static?void?main(String[]?args)?{
HashSetInteger?set=??new?HashSetInteger();//元素不可重復(fù)的無(wú)序集合
Random?rd=new?Random();//隨機(jī)產(chǎn)生器
while(set.size()7)?{
set.add(rd.nextInt(36)+1);//產(chǎn)生1~36的隨機(jī)數(shù)
//如果元素重復(fù),?那么添加不上去
}
System.out.println(set);
}
}
解法二:一維數(shù)組 ,解決產(chǎn)生7個(gè)數(shù)字, 并升序排列
int[] ? ? ?nums 數(shù)組存儲(chǔ)1~36個(gè)數(shù)組
boolean[] flags 數(shù)組存儲(chǔ)的是和nums數(shù)組一一對(duì)應(yīng)的true或者false,如果使用了就標(biāo)記為true.,如果沒(méi)有使用標(biāo)記為false,
例如 隨機(jī)產(chǎn)生了一個(gè)下標(biāo)0 ?,那么查看flags[0] ,如果是true, 那么說(shuō)明該元素已經(jīng)使用了,重新產(chǎn)生一個(gè)隨機(jī)數(shù), 如果是false ,那么表示nums[0]沒(méi)有被使用
具體代碼如下(稍微留個(gè)尾巴, 就是中不中的判斷, 可以把兩個(gè)數(shù)組都升序排序,然后元素一一比較,全部相同就是中了)
import?java.util.Arrays;
import?java.util.Random;
public?class?NumberDemo?{
public?static?void?main(String[]?args)?{
int[]?nums=?new?int[36];//長(zhǎng)度為36的數(shù)組?,默認(rèn)全是0
for?(int?i?=?0;?i??nums.length;?i++)?{//利用for循環(huán)賦值1~36
nums[i]=i+1;
}
boolean[]?flags=new?boolean[nums.length];//長(zhǎng)度和nums相同的數(shù)組,默認(rèn)值全是false?,表示全部沒(méi)有使用過(guò)
//用boolean值表示對(duì)應(yīng)的nums里的元素是否被使用
int[]?result=new?int[7];//存儲(chǔ)結(jié)果
Random?rd?=?new?Random();
for?(int?i?=?0;?i??result.length;?i++)?{
int?temp=rd.nextInt(nums.length);//隨機(jī)產(chǎn)生下標(biāo)
//System.out.println(Arrays.toString(result));
if(flags[temp])?{//如果已經(jīng)被使用,那么i-1,并在此循環(huán)
i--;
//System.out.println("號(hào)碼"+nums[temp]+"已經(jīng)存在.再次循環(huán)");
}else?{
result[i]=nums[temp];
flags[temp]=true;//標(biāo)記true表示已經(jīng)使用了
}
}
System.out.println("原始排序:"+Arrays.toString(result));
Arrays.sort(result);//升序排列
System.out.println("升序排列:"+Arrays.toString(result));
}
}
Java生成CSV文件簡(jiǎn)單操作實(shí)例
CSV是逗號(hào)分隔文件(Comma Separated Values)的首字母英文縮寫(xiě),是一種用來(lái)存儲(chǔ)數(shù)據(jù)的純文本格式,通常用于電子表格或數(shù)據(jù)庫(kù)軟件。在 CSV文件中,數(shù)據(jù)“欄”以逗號(hào)分隔,可允許程序通過(guò)讀取文件為數(shù)據(jù)重新創(chuàng)建正確的欄結(jié)構(gòu),并在每次遇到逗號(hào)時(shí)開(kāi)始新的一欄。如:
123? ?1,張三,男2,李四,男3,小紅,女? ?
Java生成CSV文件(創(chuàng)建與導(dǎo)出封裝類(lèi))
package com.yph.omp點(diǎn)抗 mon.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache點(diǎn)抗 mons.beanutils.BeanUtils;
import org.junit.Test;
/**
* Java生成CSV文件
*/
public class CSVUtil {
/**
* 生成為CVS文件
*
* @param exportData
*? ? ? ? ? ? 源數(shù)據(jù)List
* @param map
*? ? ? ? ? ? csv文件的列表頭map
* @param outPutPath
*? ? ? ? ? ? 文件路徑
* @param fileName
*? ? ? ? ? ? 文件名稱(chēng)
* @return
*/
@SuppressWarnings("rawtypes")
public static File createCSVFile(List exportData, LinkedHashMap map,
String outPutPath, String fileName) {
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
File file = new File(outPutPath);
if (!file.exists()) {
file.mkdir();
}
// 定義文件名格式并創(chuàng)建
csvFile = File.createTempFile(fileName, ".csv",
new File(outPutPath));
// UTF-8使正確讀取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(csvFile), "GBK"), 1024);
// 寫(xiě)入文件頭部
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
csvFileOutputStream
.write("\"" + (String) propertyEntry.getValue() != null ? (String) propertyEntry
.getValue() : "" + "\"");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
// 寫(xiě)入文件內(nèi)容
for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
Object row = (Object) iterator.next();
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
/*-------------------------------*/
//以下部分根據(jù)不同業(yè)務(wù)做出相應(yīng)的更改
StringBuilder sbContext = new StringBuilder("");
if (null != BeanUtils.getProperty(row,(String) propertyEntry.getKey())) {
if("證件號(hào)碼".equals(propertyEntry.getValue())){
//避免:身份證號(hào)碼 ,讀取時(shí)變換為科學(xué)記數(shù) - 解決辦法:加 \t(用Excel打開(kāi)時(shí),證件號(hào)碼超過(guò)15位后會(huì)自動(dòng)默認(rèn)科學(xué)記數(shù))
sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t");
}else{
sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()));? ? ? ? ? ? ? ? ? ? ? ? ?
}
}
csvFileOutputStream.write(sbContext.toString());
/*-------------------------------*/? ? ? ? ? ? ? ? ?
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
/**
* 下載文件
*
* @param response
* @param csvFilePath
*? ? ? ? ? ? 文件路徑
* @param fileName
*? ? ? ? ? ? 文件名稱(chēng)
* @throws IOException
*/
public static void exportFile(HttpServletRequest request,
HttpServletResponse response, String csvFilePath, String fileName)
throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/csv;charset=GBK");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) 0) {
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e1) {
System.out.println(e1);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
}
}
/**
* 刪除該目錄filePath下的所有文件
*
* @param filePath
*? ? ? ? ? ? 文件目錄路徑
*/
public static void deleteFiles(String filePath) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
}
/**
* 刪除單個(gè)文件
*
* @param filePath
*? ? ? ? ? ? 文件目錄路徑
* @param fileName
*? ? ? ? ? ? 文件名稱(chēng)
*/
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i files.length; i++) {
if (files[i].isFile()) {
if (files[i].getName().equals(fileName)) {
files[i].delete();
return;
}
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void createFileTest() {
List exportData = new ArrayListMap();
Map row1 = new LinkedHashMapString, String();
row1.put("1", "11");
row1.put("2", "12");
row1.put("3", "13");
row1.put("4", "14");
exportData.add(row1);
row1 = new LinkedHashMapString, String();
row1.put("1", "21");
row1.put("2", "22");
row1.put("3", "23");
row1.put("4", "24");
exportData.add(row1);
LinkedHashMap map = new LinkedHashMap();
map.put("1", "第一列");
map.put("2", "第二列");
map.put("3", "第三列");
map.put("4", "第四列");
String path = "d:/export";
String fileName = "文件導(dǎo)出";
File file = CSVUtil.createCSVFile(exportData, map, path, fileName);
String fileNameNew = file.getName();
String pathNew = file.getPath();
System.out.println("文件名稱(chēng):" + fileNameNew );
System.out.println("文件路徑:" + pathNew );
}
}
//注:BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t" ,只為解決數(shù)字格式超過(guò)15位后,在Excel中打開(kāi)展示科學(xué)記數(shù)問(wèn)題。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GradeStatistic {
public static void main(String[] args) {
GradeStatistic gs = new GradeStatistic();
ListMark list = new ArrayListMark();
float sum = 0;
while(true){
Scanner sc = new Scanner(System.in);
System.out.print("Please input student name: ");
String name = sc.nextLine();
if(name.equals("end")){
break;
}
System.out.print("Please input student score: ");
float score = sc.nextFloat();
sum += score;
list.add(gs.new Mark(name, score));
}
float max = list.get(0).getScore();
float min = list.get(0).getScore();
for(Mark mark: list){
if(max mark.getScore()){
max = mark.getScore();
}
if(min mark.getScore()){
min = mark.getScore();
}
}
float average = sum / list.size();
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
private class Mark{
private String name;
private float score;
public Mark(String name, float score){
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public float getScore() {
return score;
}
}
}
----------------------
Please input student name: Zhang san
Please input student score: 100
Please input student name: Li Si
Please input student score: 91
Please input student name: Ec
Please input student score: 35
Please input student name: ma qi
Please input student score: 67
Please input student name: end
Average is: 73.25
Max is: 100.0
Min is: 35.0