大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
/**
专注于为中小企业提供成都做网站、成都网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业顺城免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千余家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
* 文件名:Operation.java 2014-1-2 下午3:06:37
* @author Administrator
*/
package cc.icoc.javaxu.action;
import java.util.ArrayList;
import java.util.Scanner;
import cc.icoc.javaxu.datas.StudentInfo;
/**
* @author 许仕永
* 创建时间: 2014 2014-1-2 下午3:06:37
*/
public class Operation
{
int stuNo,stuAge;
String stuName,stuClass,stuSex;
ArrayListStudentInfo list;
/**程序入口
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Operation().operation();
}
private int inputInt()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private String inputStr()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
private void operation()
{
// TODO Auto-generated method stub
if(list == null)
{
list = new ArrayListStudentInfo();
}
while(true)
{
System.out.println("\t\t\t学生信息管理系统\n");
System.out.println("1.信息查阅");
System.out.println("2.信息查询");
System.out.println("3.信息录入");
System.out.println("4.退出系统");
int what = inputInt();
if ( what == 1 )
{
getInfo();
} else if ( what == 2 )
{
allSerach();
} else if ( what == 3 )
{
inputInfo();
} else if( what == 4 )
{
System.out.println("已经退出系统");
System.exit(0);
}
}
}
/**
* 获取全部学生的信息列表
*/
private void getInfo()
{
if(!list.isEmpty())
{
for ( int i = 0; i list.size(); i++ )
{
System.out.println(list.get(i));
}
}
}
/**
* 执行查找
*/
private void allSerach()
{
System.out.println("1.输入学号进行查询");
System.out.println("2.输入姓名进行查询");
int what = inputInt();
if(what == 1)
{
System.out.println("请输入学号:");
search(inputInt());
}
else
{
System.out.println("请输入姓名:");
search(inputStr());
}
}
/**
* 按学生姓名查询学生信息
* @param name 学生姓名
*/
private StudentInfo search(String name)
{
for ( int i = 0; i list.size(); i++ )
{
if(list.get(i).getStuName().equals(name))
{
System.out.println(list.get(i));
return list.get(i);
}
}
System.out.println("未查询到该名字的学生");
return null;
}
/**
* 按学号查询学生信息
* @param id 学号
*/
private StudentInfo search(int id)
{
for ( int i = 0; i list.size(); i++ )
{
if(list.get(i).getStuNo()==id)
{
System.out.println(list.get(i));
return list.get(i);
}
}
System.out.println("未查询到该学号的学生");
return null;
}
/**
* 录入学生信息
*/
private void inputInfo()
{
try
{
System.out.print("请输入学生学号:\n");
stuNo = inputInt();
System.out.print("请输入学生姓名:\n");
stuName = inputStr();
System.out.print("请输入学生性别:\n");
stuSex = inputStr();
System.out.print("请输入学生年龄:\n");
stuAge = inputInt();
System.out.print("请输入学生班级:\n");
stuClass = inputStr();
list.add(new StudentInfo(stuNo, stuAge, stuName, stuSex, stuClass));
} catch (Exception e)
{
// TODO: handle exception
System.out.println("不允许为空,请重新输入");
}
}
}
package cc.icoc.javaxu.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Stu
{
int countStu = 0;
int sum = 0;
int avg = 0;
ListStuBean list = new ArrayListStu.StuBean();
public static void main(String[] args)
{
new Stu().go();
}
private void go()
{
A:while(true)
{
//构造实体Bean来存储学生成绩
StuBean bean = new StuBean();
System.out.println("请输入成绩:");
System.out.println("语文:");
bean.setYuwen(scanner());
System.out.println("数学:");
bean.setMath(scanner());
//获取英语成绩
System.out.println("英语:");
bean.setEnglish(scanner());
//存入容器
list.add(bean);
for ( int i = 0; i list.size(); i++ )
{
sum += list.get(i).english+list.get(i).math+list.get(i).yuwen;
}
avg = sum / (3*list.size());
System.out.println("当前有"+list.size()+"条学生记录,所有学生总分="+sum+"平均分为"+avg);
//输入y继续录入学生信息,输入x退出
System.out.println("\n已成功录入一个学生的数据,是否继续/退出(y/x)");
if("x".equals(scannerString()))
break A;
}
}
/**输入*/
private int scanner()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
/**输入*/
private String scannerString()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
class StuBean
{
int math;
int yuwen;
int english;
public int getMath()
{
return math;
}
public void setMath(int math)
{
this.math = math;
}
public int getYuwen()
{
return yuwen;
}
public void setYuwen(int yuwen)
{
this.yuwen = yuwen;
}
public int getEnglish()
{
return english;
}
public void setEnglish(int english)
{
this.english = english;
}
}
}
/**
* 文件名:StudentInfo.java 2014-1-2 下午3:07:29
* @author Administrator
*/
package cc.icoc.javaxu.datas;
/**
* @author 许仕永
* 创建时间: 2014 2014-1-2 下午3:07:29
*/
public class StudentInfo
{
int stuNo,stuAge;
String stuName,stuSex,stuClass;
public StudentInfo(int stuNo, int stuAge, String stuName, String stuSex, String stuClass)
{
super();
this.stuNo = stuNo;
this.stuAge = stuAge;
this.stuName = stuName;
this.stuSex = stuSex;
this.stuClass = stuClass;
}
public int getStuNo()
{
return stuNo;
}
public void setStuNo(int stuNo)
{
this.stuNo = stuNo;
}
public int getStuAge()
{
return stuAge;
}
public void setStuAge(int stuAge)
{
this.stuAge = stuAge;
}
public String getStuName()
{
return stuName;
}
public void setStuName(String stuName)
{
this.stuName = stuName;
}
public String getStuSex()
{
return stuSex;
}
public void setStuSex(String stuSex)
{
this.stuSex = stuSex;
}
public String getStuClass()
{
return stuClass;
}
public void setStuClass(String stuClass)
{
this.stuClass = stuClass;
}
@Override
public String toString()
{
// TODO Auto-generated method stub
String s = "学号:"+getStuNo()+"\t姓名:"+getStuName()+" \t性别:"+getStuSex()+"\t年龄:"+getStuAge()+"\t班级:"+getStuClass();
return s;
}
}
hotspot 虚拟机(咱们平时开发用的sun公司的虚拟机,其他两大商用虚拟机是BEA的JRockit和IBM的J9)里面两个字节来限制大小,所以最多65536行,超过javac会无法编译。而且一个Java方法不能超过64k。一般一个Java类不要有太多行数,如果一个Java代码超过几千甚至过万,个人觉得应该考虑一些代码优化方式,比如继承;或者重新构思这个类。代码行数太多可读性查,不利于维护。
题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?
这个题目,下面我会贴出来两种代码。其实这个题目,我烦了简单计算,想搞得有趣味性一点,结果耽误了好几天时间,最后发现搞的也不好。
先第一种,为了解题而解题。
==== Main.java ====
public class Main {
private double TotalHeight = 100;
private double CurHeight = 50;
public void drop(int times) {
if ((times - 1) == 0) {
return;
}
setTotalHeight(getTotalHeight() + 2 * getCurHeight());
setCurHeight(getCurHeight() / 2);
drop(times - 1);
}
public double getTotalHeight() {
return TotalHeight;
}
public void setTotalHeight(double totalHeight) {
TotalHeight = totalHeight;
}
public double getCurHeight() {
return CurHeight;
}
public void setCurHeight(double curHeight) {
CurHeight = curHeight;
}
public static void main(String[] args) {
Main main = new Main();
main.drop(2);
System.out.println("Total height is " +
main.getTotalHeight());
System.out.println("Current height is " +
main.getCurHeight());
}
}
==== 然后是第二种 =====
==== Main.java ====
package main;
import javax.swing.JFrame;
import panel.BallPanel;
import time.Delay;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
}
public static void main(String[] args) {
Delay delay = new Delay();
MainFrame frame = new MainFrame("Hello JFrame");
BallPanel ballPanel = new BallPanel();
frame.add(ballPanel);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
delay.initDelay();
ballPanel.setDelay(delay.getDelay());
ballPanel.loopDrop(0);
}
}
==== Delay.java ====
package time;
public class Delay {
public void initDelay() {
int g = 10;
int i = 0;
double s, t, t0 = 0.0;
delay = new int[100];
for (s = 100; s 10100; s += 100) {
t = Math.sqrt(2 * s / g);
delay[i++] = (int) ((t - t0) * 100);
t0 = t;
}
}
public int[] getDelay() {
return delay;
}
private int delay[];
}
==== BallPanel.java ====
package panel;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class BallPanel extends JPanel {
public BallPanel() {
super();
}
public void paint(Graphics g) {
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.BLUE);
g.fillOval(250, ballCenter, 30, 30);
}
public void loopDrop(int height) {
int i;
if (this.height == height) { // At bottom
for (i = 0; i targetHeight; i += MUL) {
ballCenter = this.height - i;
this.repaint();
try {
Thread.sleep(delay[(targetHeight - i - 1) / MUL]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
loopDrop(this.height - i);
} else { // At top
for (i = height; i this.height; i += MUL) {
ballCenter = i;
this.repaint();
try {
Thread.sleep(delay[(i - height) / MUL]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
targetHeightV = targetHeightV / 2;
targetHeight = targetHeightV;
if (targetHeight != 0) {
loopDrop(i);
}
}
}
public void setDelay(int delay[]) {
this.delay = delay;
}
private int extracted() {
return 100 * MUL;
}
private int targetHeight = extracted();
private int targetHeightV = extracted();
private int ballCenter = 0;
private int height = extracted();
private int delay[];
private final int MUL = 4;
}
其实所谓的第二种,是用的JFrame在JPanel上画图,直观的展示出来每次弹起来的效果。因为100像素实在太小了,所以我做了一个变量MUL,相
当于是等比例扩大的效果。问题就是弹不到10次距离就用光了,所以。。。。。权当娱乐了。。当然可以等比例在放大,例如100M看成是10000像素,这
样能多弹几次。这个程序,最后球就在那里不动了,程序不会自己退出。
我有计算器程序
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的计算器。MyCalculator 继承于 JFrame,是计算器的界面
*/
public class Calculator extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
}
};
public Calculator(String title) throws HeadlessException {
super(title); // 调用父类构造方法
setupFrame(); // 调整窗体属性
setupControls(); // 创建控件
}
private void setupControls() {
setupDisplayPanel(); // 创建文本面板
setupButtonsPanel(); // 创建按钮面板
}
// 创建按钮面板并添加按钮
private void setupButtonsPanel() {
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示这个位置没有按钮
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 为空,则表示创建一个空面板。否则创建一个按钮。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener); // 为按钮添加侦听器
panel.add(b);
}
}
}
// 设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 调整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右对齐
textbox.setEditable(false); // 文本框只读
textbox.setBackground(Color.white); // 文本框背景色为白色
}
// 调整窗体
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 当窗体关闭时程序结束
this.setLocation(100, 50); // 设置窗体显示在桌面上的位置
this.setSize(300, 200); // 设置窗体大小
this.setResizable(false); // 窗体大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Calculator frame = new Calculator("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
}
}
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
*/
class CalculatorCore {
private String displayText = "0"; // 要显示的文本
boolean reset = true;
int MaxLen = 30;
private BigDecimal number1, number2;
private String operator;
private HashMapString, Operator operators = new HashMapString, Operator();
private HashMapString, Processor processors = new HashMapString, Processor();
CalculatorCore() {
setupOperators();
setupProcessors();
}
// 为每种命令添加处理方式
private void setupProcessors() {
processors.put("[0-9]", new Processor() {
public void calculate(String command) {
numberClicked(command);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("=", new Processor() {
public void calculate(String command) {
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor() {
public void calculate(String command) {
operatorClicked(command);
}
});
processors.put("C", new Processor() {
public void calculate(String command) {
clearClicked();
}
});
processors.put("CE", new Processor() {
public void calculate(String command) {
clearErrorClicked();
}
});
}
// 为每种 operator 添加处理方式
private void setupOperators() {
operators.put("+", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.add(number2);
}
});
operators.put("-", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.subtract(number2);
}
});
operators.put("*", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.multiply(number2);
}
});
operators.put("/", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
// 根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 当按下 CE 时
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 当按下 C 时,将计算器置为初始状态。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 当按下 = 时
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 计算结果
/**
*
*/
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
try {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
} catch (RuntimeException e) {
clearClicked();//将计算器置为初始状态
JOptionPane.showMessageDialog(null,"不能用零作除数","出错了",JOptionPane.OK_OPTION);
//e.printStackTrace();
}
}
}
// 当按下 +-*/ 时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 当按下 . 时
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText += ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 当按下 0-9 时
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
if(displayText.length() MaxLen)
displayText += command;
else
JOptionPane.showMessageDialog(null,"输入的数字太长了","出错了",JOptionPane.OK_OPTION);
}
reset = false;
}
// 运算符处理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按钮处理接口
interface Processor {
void calculate(String command);
}
}
这个计算器可是我自己写了好几天才写好的耶,你能在网上找到?
计算器:
// Calculator.java
public class Calculator {
private static final char NO_OP = '\0';
private static final char PLUS = '+';
private static final char SUBTRACT = '-';
private static final char MULTIPLY = '*';
private static final char DIVIDE = '/';
private float number1 = 0.0F;
//private float number2 = Float.NaN;
private char operator = NO_OP;
//等于运算
public String opEquals(String number) {
float result;
if ( operator == NO_OP ) {
result = parseNumber(number);
} else {
result = performOperation(parseNumber(number));
}
operator = NO_OP;
number1 = result;
return Float.toString(result);
}
//加法运算
public String opAdd(String number) {
float result;
if ( operator == NO_OP ) {
result = parseNumber(number);
} else {
result = performOperation(parseNumber(number));
}
operator = PLUS;
number1 = result;
return Float.toString(result);
}
//减法运算
public String opSubtract(String number) {
float result;
if ( operator == NO_OP ) {
result = parseNumber(number);
} else {
result = performOperation(parseNumber(number));
}
operator = SUBTRACT;
number1 = result;
return Float.toString(result);
}
//乘法运算
public String opMultiply(String number) {
float result;
if ( operator == NO_OP ) {
result = parseNumber(number);
} else {
result = performOperation(parseNumber(number));
}
operator = MULTIPLY;
number1 = result;
return Float.toString(result);
}
//除法运算
public String opDivide(String number) {
float result;
if ( operator == NO_OP ) {
result = parseNumber(number);
} else {
result = performOperation(parseNumber(number));
}
operator = DIVIDE;
number1 = result;
return Float.toString(result);
}
//处理运算符
private float performOperation(float number2) {
float result = 0.0F;
switch ( operator ) {
case PLUS:
result = number1 + number2;
break;
case SUBTRACT:
result = number1 - number2;
break;
case MULTIPLY:
result = number1 * number2;
break;
case DIVIDE:
result = number1 / number2;
break;
}
return result;
}
//将字符串类型转换为浮点型
private static float parseNumber(String number) {
float real_number;
try {
real_number = Float.parseFloat(number);
} catch (NumberFormatException e) {
real_number = Float.NaN;
}
return real_number;
}
}
GUI程序:
// CalculatorGUI.java
import java.awt.*;
import java.awt.event.*;
public class CalculatorGUI {
// 定义按钮
private Button key0, key1, key2, key3, key4;
private Button key5, key6, key7, key8, key9;
private Button keyequal, keyplus, keyminus;
private Button keyperiod, keymult, keydiv;
// 定义存放按钮的区域
private Panel buttonArea;
// 定义存放运算结果的区域
private Label answer;
// 用来实现运算功能的类的对象实例化
private Calculator calculator;
private boolean readyForNextNumber;
public CalculatorGUI() {
calculator = new Calculator();
readyForNextNumber = true;
answer = new Label("0.0",Label.RIGHT);
key0 = new Button("0");
key1 = new Button("1");
key2 = new Button("2");
key3 = new Button("3");
key4 = new Button("4");
key5 = new Button("5");
key6 = new Button("6");
key7 = new Button("7");
key8 = new Button("8");
key9 = new Button("9");
keyequal = new Button("=");
keyplus = new Button("+");
keyminus = new Button("-");
keymult = new Button("*");
keydiv = new Button("/");
keyperiod = new Button(".");
buttonArea = new Panel();
}
public void launchFrame() {
buttonArea.setLayout(new GridLayout(4,4));
buttonArea.add(key7);
buttonArea.add(key8);
buttonArea.add(key9);
buttonArea.add(keyplus);
buttonArea.add(key4);
buttonArea.add(key5);
buttonArea.add(key6);
buttonArea.add(keyminus);
buttonArea.add(key1);
buttonArea.add(key2);
buttonArea.add(key3);
buttonArea.add(keymult);
buttonArea.add(key0);
buttonArea.add(keyperiod);
buttonArea.add(keyequal);
buttonArea.add(keydiv);
// 设置事件接收句柄
OpButtonHanlder op_handler = new OpButtonHanlder();
NumberButtonHanlder number_handler = new NumberButtonHanlder();
key0.addActionListener(number_handler);
key1.addActionListener(number_handler);
key2.addActionListener(number_handler);
key3.addActionListener(number_handler);
key4.addActionListener(number_handler);
key5.addActionListener(number_handler);
key6.addActionListener(number_handler);
key7.addActionListener(number_handler);
key8.addActionListener(number_handler);
key9.addActionListener(number_handler);
keyperiod.addActionListener(number_handler);
keyplus.addActionListener(op_handler);
keyminus.addActionListener(op_handler);
keymult.addActionListener(op_handler);
keydiv.addActionListener(op_handler);
keyequal.addActionListener(op_handler);
// 新建一个帧,并且加上消息监听
Frame f = new Frame("计算器");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setSize(200, 200);
f.add(answer, BorderLayout.NORTH);
f.add(buttonArea, BorderLayout.CENTER);
f.setVisible (true);
}
//响应按钮事件,并根据不同的按钮事件进行不同的运算
private class OpButtonHanlder implements ActionListener {
public void actionPerformed(ActionEvent event) {
char operator = event.getActionCommand().charAt(0);
String result = "";
switch ( operator ) {
case '+':
result = calculator.opAdd(answer.getText());
break;
case '-':
result = calculator.opSubtract(answer.getText());
break;
case '*':
result = calculator.opMultiply(answer.getText());
break;
case '/':
result = calculator.opDivide(answer.getText());
break;
case '=':
result = calculator.opEquals(answer.getText());
break;
}
answer.setText(result);
readyForNextNumber = true;
}
}
//处理连续运算时主界面的显示
private class NumberButtonHanlder implements ActionListener {
public void actionPerformed(ActionEvent event) {
if ( readyForNextNumber ) {
answer.setText(event.getActionCommand());
readyForNextNumber = false;
} else {
answer.setText(answer.getText() + event.getActionCommand().charAt(0));
}
}
}
//主函数,也是该应用程序的执行入口处
public static void main(String[] args) {
CalculatorGUI calcGUI = new CalculatorGUI();
calcGUI.launchFrame();
}
}
注意:运行的是GUI程序