走上java之路以及两个小程序

学习Java的感受

因为是计算机专业的学生,开始计划着自学Java,从买书、看视频、到自己完成一些小项目,总感觉却了些什么,对Java这门语言还是感觉比较陌生,也可以说理解的还不够透彻吧。一次校企合作的培训参观,上了一天的培训课后,终于意识到了自己所缺少的东西:对Java这门语言没有系统的了解,只是停留在表面的会用,但不理解这么做的理由。这次的参观学习,让我重新找到了方向,参加一个培训也不是必不可少的,但是却是见效最快的,毕竟大部分人都会存在惰性,若不是现实处境所迫,也没有人会去强迫自己,谁不想着玩呢。当然正是这种强迫,将会成为学习的一种动力。自学总会遇到一些或多或少的问题,百度的途径不一定可以解决所有的问题,而线下的培训,就很好的解决了这个问题。我们更多的是去学习这种解决办法的方法,毕竟以后进入企业,就没有老师来专门给你解决问题了,还是得靠自己。学习java最重要的工具——API文档,随着jdk版本的迭代,API文档也逐渐完善,大部分内容是比较准确的,学会查文档,也是学习java的基础。课上的学习,加上必要的练习,以及坚持课后经常的复习,相信在牢固的基础之后,学更复杂的内容和框架,就不会太困难了。经过一个星期的学习,学到了很多常用类的用法,也在老师打的带领下写了几个有趣的小程序,在这里分享一下。

小程序一:目录遍历

要求对一个指定的目录进行遍历,获取该目录下所有的文件,并且,考虑该目录下还存在子目录?要求以文件树的形式输出目录结构:
在这里插入图片描述
具体实现代码:

import java.io.File;

public class ReadFile {

	/**
	 * 	获取目录和文件名
	 * @param file
	 * @param level
	 */
	public void getFileName(File file,int level) {
		//获取该目录的文件(目录)列表
		File[] files = file.listFiles();
		level++;

		if(files != null) {	
			for(File f:files) {
				//根据level分层打印--
				for (int i = 0; i < level; i++) {
						System.out.print("--");
					}
					System.out.println(f.getName());
					//判断该对象是否是目录,是目录则递归
				if(f.isDirectory()) {
					getFileName(f, level);
				}
			}
			
		}
	}

	public static void main(String[] args) {

		new ReadFile().getFileName(new File("D:\\新建文件夹\\java\\test"),0);
	}
}

小程序二:微信红包生成算法实现

要求实现是一个微信红包生成的算法,通过提供一个总金额,以及红包数,要求根据红包总数随机生成金额不等的红包,并输出;要求输出的每个红包金额总和要等于总金额,要求最低金额不能少于0.01元。
在这里插入图片描述
具体实现代码:

/**
 * 	红包类
 * @author 半夏微凉
 *
 */
public class RedPacket {

	/**总金额*/
	private String sumMoney;
	/**红包总数*/
	private int count;
	
	public RedPacket(String sumMoney,int count) {
		this.sumMoney = sumMoney;
		this.count = count;
	}

	public String getSumMoney() {
		return sumMoney;
	}

	public void setSumMoney(String sumMoney) {
		this.sumMoney = sumMoney;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}



/**
 * 	自定义红包异常
 * @author 半夏微凉
 *
 */
public class RedPacketException extends Exception{

	public RedPacketException() {
		
	}
	
	public RedPacketException(String message) {
		super(message);
	}

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Random;

public class RedPacketManager {

	private Random r = new Random();
	
	public ArrayList<BigDecimal> genPacket(RedPacket rp) throws RedPacketException{
		//定义BigDecimal类型集合存储每个人所获得的红包金额
		ArrayList<BigDecimal> list = new ArrayList<>();
		//将保底的0.01元包装成BigDecimal类型
		BigDecimal money = new BigDecimal("0.01");
		//用于存储前n-1个人所分红包的总金额
		BigDecimal sends = new BigDecimal("0");
		//获取总金额的最小值
		double minMoney = money.multiply(new BigDecimal(rp.getCount())).doubleValue();
		//将字符串类型总金额包装成BigDecimal
		BigDecimal totalMoney = new BigDecimal(rp.getSumMoney());
		//判断红包的最小值是否超过了总金额(总金额不够分)
		if(minMoney > totalMoney.doubleValue()) {
			throw new RedPacketException("每个红包不能少于0.01元");
		}
		if(minMoney == totalMoney.doubleValue()) {
			//最低金额正好等于总金额
			for (int i = 0; i < rp.getCount(); i++) {
				list.add(new BigDecimal("0.01"));
			}
			return list;
		}
		//总金额超过每个人最低金额
		//获取分配的随机比例
		double[] scales = randomSale(rp.getCount());
		//给n-1个人分红包
		for (int i = 0; i < scales.length - 1; i++) {
			//根据比例计算每个红包分得的金额
			money = totalMoney.multiply(new BigDecimal(scales[i])).setScale(2,BigDecimal.ROUND_HALF_EVEN);
			//累计已经分配的金额
			sends = sends.add(money);
			//将每个人所分的金额加入到集合中
			list.add(money);
		}
		list.add(totalMoney.subtract(sends));
		return list;
	}
	
	/**
	 * 	随机生成比例
	 * @param n
	 * @return
	 */
	public double[] randomSale(int n) {
		//累计总的随机值
		double total = 0;
		//临时数组存储每个红包的随机比例
		double[] scales = new double[n];
		for (int i = 0; i < scales.length; i++) {
			//随机获得一个1~100的整数
			int rint = r.nextInt(100)+1;
			//将每个随机数分别存入数组
			scales[i] = rint;
			//计算总的随机值
			total += rint;
		}
		//计算比例
		for (int i = 0; i < scales.length; i++) {
			scales[i] = scales[i] / total;
		}
		return scales;		
	}
	
	public static void main(String[] args) throws RedPacketException {
		
		ArrayList<BigDecimal> list = new RedPacketManager().genPacket(new RedPacket("10", 5));
		
		for(BigDecimal bd:list) {
			System.out.println(NumberFormat.getCurrencyInstance().format(bd)+"\t");
		}
	}

当然基本功能实现了,但也存在一些不足:例如,红包数较少时,有可能出现¥0.00的红包。

总结

在学习了一些基础知识后,就可以动手做一些有趣的小程序了,这些小程序不仅可以提升我们学习的乐趣,还能加强我们所学的知识,我觉得很有必要。相信随着不断的学习,我也可以学到更多的知识,最终走上求职之路。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的五子棋人机对弈小程序的示例代码,基于 Java Swing 编写。 ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Gobang extends JFrame implements ActionListener, MouseListener { private static final long serialVersionUID = 1L; private JPanel panel; private JButton button; private JLabel label1, label2; private int[][] chessBoard; private boolean isBlack = true; private boolean gameOver = false; private final int ROWS = 15; private final int COLS = 15; private final int SIZE = 30; private final int MARGIN = 30; public Gobang() { setTitle("五子棋"); setSize(600, 600); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); init(); setVisible(true); } private void init() { panel = new JPanel(); panel.setBackground(new Color(255, 204, 102)); panel.setLayout(null); panel.addMouseListener(this); button = new JButton("重新开始"); button.addActionListener(this); button.setBounds(450, 120, 100, 40); label1 = new JLabel("黑方先手"); label1.setFont(new Font("宋体", Font.BOLD, 20)); label1.setBounds(450, 200, 150, 40); label2 = new JLabel("轮到黑方"); label2.setFont(new Font("宋体", Font.BOLD, 20)); label2.setBounds(450, 250, 150, 40); panel.add(button); panel.add(label1); panel.add(label2); add(panel); chessBoard = new int[ROWS][COLS]; } private void drawChessBoard(Graphics g) { for (int i = 0; i <= ROWS; i++) { g.drawLine(MARGIN, MARGIN + i * SIZE, MARGIN + COLS * SIZE, MARGIN + i * SIZE); } for (int i = 0; i <= COLS; i++) { g.drawLine(MARGIN + i * SIZE, MARGIN, MARGIN + i * SIZE, MARGIN + ROWS * SIZE); } } private void drawChessPiece(Graphics g, int row, int col, boolean isBlack) { int x = MARGIN + col * SIZE; int y = MARGIN + row * SIZE; g.setColor(isBlack ? Color.BLACK : Color.WHITE); g.fillOval(x - SIZE / 2, y - SIZE / 2, SIZE, SIZE); } private boolean checkWin(int row, int col) { int count = 1; int color = chessBoard[row][col]; int r, c; // 检查水平方向 r = row; c = col - 1; while (c >= 0 && chessBoard[r][c] == color) { count++; c--; } c = col + 1; while (c < COLS && chessBoard[r][c] == color) { count++; c++; } if (count >= 5) { return true; } // 检查竖直方向 count = 1; r = row - 1; c = col; while (r >= 0 && chessBoard[r][c] == color) { count++; r--; } r = row + 1; while (r < ROWS && chessBoard[r][c] == color) { count++; r++; } if (count >= 5) { return true; } // 检查左斜方向 count = 1; r = row - 1; c = col - 1; while (r >= 0 && c >= 0 && chessBoard[r][c] == color) { count++; r--; c--; } r = row + 1; c = col + 1; while (r < ROWS && c < COLS && chessBoard[r][c] == color) { count++; r++; c++; } if (count >= 5) { return true; } // 检查右斜方向 count = 1; r = row - 1; c = col + 1; while (r >= 0 && c < COLS && chessBoard[r][c] == color) { count++; r--; c++; } r = row + 1; c = col - 1; while (r < ROWS && c >= 0 && chessBoard[r][c] == color) { count++; r++; c--; } if (count >= 5) { return true; } return false; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { chessBoard = new int[ROWS][COLS]; isBlack = true; gameOver = false; label1.setText("黑方先手"); label2.setText("轮到黑方"); panel.repaint(); } } @Override public void mouseClicked(MouseEvent e) { if (gameOver) { return; } int x = e.getX(); int y = e.getY(); if (x < MARGIN || x > MARGIN + COLS * SIZE || y < MARGIN || y > MARGIN + ROWS * SIZE) { return; } int row = Math.round((float) (y - MARGIN) / SIZE); int col = Math.round((float) (x - MARGIN) / SIZE); if (chessBoard[row][col] != 0) { return; } chessBoard[row][col] = isBlack ? 1 : 2; panel.repaint(); if (checkWin(row, col)) { gameOver = true; String winner = isBlack ? "黑方" : "白方"; JOptionPane.showMessageDialog(panel, winner + "获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return; } isBlack = !isBlack; label1.setText(isBlack ? "黑方先手" : "白方先手"); label2.setText(isBlack ? "轮到黑方" : "轮到白方"); if (!isBlack) { // AI 下棋 int[] pos = computeNextMove(); row = pos[0]; col = pos[1]; chessBoard[row][col] = 2; panel.repaint(); if (checkWin(row, col)) { gameOver = true; JOptionPane.showMessageDialog(panel, "白方获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE); return; } isBlack = !isBlack; label1.setText(isBlack ? "黑方先手" : "白方先手"); label2.setText(isBlack ? "轮到黑方" : "轮到白方"); } } private int[] computeNextMove() { int[] pos = new int[2]; // TODO: AI 算法 return pos; } @Override public void paint(Graphics g) { super.paint(g); drawChessBoard(g); for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { if (chessBoard[i][j] == 1) { drawChessPiece(g, i, j, true); } else if (chessBoard[i][j] == 2) { drawChessPiece(g, i, j, false); } } } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} public static void main(String[] args) { new Gobang(); } } ``` 这个程序由一个主窗口和一个 JPanel 组成。主窗口负责创建并显示 JPanel,JPanel 则绘制棋盘和棋子,并处理用户交互和游戏逻辑。 在 JPanel 的构造函数中,我们初始化了棋盘数组 `chessBoard`,表示棋盘上每个格子的状态。1 表示黑子,2 表示白子,0 表示空格。我们还添加了一个按钮和两个标签,用于重新开始游戏和显示游戏状态。 在 `drawChessBoard` 方法中,我们使用 Graphics 类的 `drawLine` 方法绘制棋盘的线条。 在 `drawChessPiece` 方法中,我们使用 Graphics 类的 `fillOval` 方法绘制棋子。黑子用黑色填充,白子用白色填充。 在 `checkWin` 方法中,我们检查棋盘上某个格子所处的行、列、左斜方向和右斜方向是否有连续五个相同颜色的棋子。如果有,则游戏结束。 在 `actionPerformed` 方法中,我们对重新开始按钮的点击事件进行处理。重新初始化棋盘数组、重置游戏状态和标签,并调用 JPanel 的 `repaint` 方法刷新界面。 在 `mouseClicked` 方法中,我们处理鼠标点击事件。如果游戏已经结束或点击了棋盘外部或已经有棋子存在,则不做任何处理。否则,我们根据鼠标点击坐标计算出所在的行和列,将这个位置设为当前玩家下的棋子。然后检查游戏是否结束,并切换当前玩家。如果当前玩家是电脑,则调用 `computeNextMove` 方法计算出下一个位置,并执行相同的操作。 在 `paint` 方法中,我们使用 Graphics 类的 `paint` 方法绘制棋盘和棋子。 在 `computeNextMove` 方法中,我们需要实现一个 AI 算法,来计算出电脑下一步应该走的位置。这里我们暂时留空,可以自己实现一个简单的算法,比如随机生成一个空白位置,作为电脑的下一步。 最后,在 `main` 方法中,我们创建一个新的 Gobang 对象,启动程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值