下面兩個(gè)可以么,是我做實(shí)驗(yàn)答辯時(shí)用到的!
在順慶等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都做網(wǎng)站、成都網(wǎng)站制作 網(wǎng)站設(shè)計(jì)制作定制網(wǎng)站開發(fā),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),營(yíng)銷型網(wǎng)站,成都外貿(mào)網(wǎng)站制作,順慶網(wǎng)站建設(shè)費(fèi)用合理。
import?java.awt.*;//AWT核心包
import?java.awt.event.*;//提供事件類和監(jiān)聽器
public?class?Counter?extends?Frame?implements?ActionListener
{
TextField?t=new?TextField("");//文本框
Panel?p1=new?Panel();//new一個(gè)panel,用于存放數(shù)字鍵和符號(hào)鍵。
Panel?p2=new?Panel();//new一個(gè)panel,用于存放開方、平方、和清除鍵。
Button[]?b=new?Button[10];//實(shí)例化Button對(duì)象
Button?bAdd=new?Button("加");
Button?bSub=new?Button("減");
Button?bMul=new?Button("乘以");
Button?bPoint=new?Button(".");
Button?bDiv=new?Button("除以");
Button?bEqual=new?Button("等於");
Button?bSqrt=new?Button("開方");
Button?bPow=new?Button("平方");
Button?bNull=new?Button("清除");
String?str1="";?????//str1和str2存放兩個(gè)輸入的數(shù)
String?str2="";
String?operator=null;???//存放加減乘除以及開平方的符號(hào)
boolean?first=true;????//檢驗(yàn)輸入的是否為第一個(gè)數(shù)
int?countOper=0;????//累計(jì)輸入符號(hào)的個(gè)數(shù),連加連減等操作中會(huì)用到
double?result=0.0;????//暫存結(jié)果
double?num1=0.0,num2=0.0;??//兩個(gè)輸入的數(shù)做運(yùn)算時(shí)轉(zhuǎn)化為double存放
boolean?error=false;???//檢驗(yàn)除數(shù)是否為0
//構(gòu)造方法
public?Counter()
{
Frame?s=new?Frame("計(jì)算器");//創(chuàng)建Frame
for(int?i=0;i10;i++)//利用for循環(huán)將數(shù)字鍵添加進(jìn)p1中
{
b[i]=new?Button(String.valueOf(i));
p1.add(b[i]);
b[i].setActionCommand("number");
b[i].setForeground(new?Color(150,20,20));
b[i].addActionListener(this);//調(diào)用addActionListener()方法注冊(cè)事件監(jiān)聽器
}
p1.add(bPoint);
bPoint.setActionCommand("number");
p1.add(bAdd);?//數(shù)字鍵,符號(hào)鍵放置在panel的p1中
p1.add(bSub);
p1.add(bMul);
p1.add(bDiv);
p1.add(bEqual);
p2.add(bSqrt);//開方鍵,平方鍵,清除鍵放置在panel的p2中
p2.add(bPow);
p2.add(bNull);
bAdd.setActionCommand("oper");
bSub.setActionCommand("oper");
bMul.setActionCommand("oper");
bDiv.setActionCommand("oper");
bAdd.setForeground(Color.red);//為組鍵設(shè)計(jì)顏色
bSub.setForeground(Color.red);
bMul.setForeground(Color.red);
bDiv.setForeground(Color.red);
bPoint.setForeground(Color.black);
bEqual.setForeground(Color.red);
bSqrt.setForeground(Color.blue);
bPow.setForeground(Color.blue);
bNull.setForeground(Color.blue);
bAdd.addActionListener(this);//調(diào)用addActionListener()方法注冊(cè)事件監(jiān)聽器
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bPoint.addActionListener(this);
bEqual.addActionListener(this);
bSqrt.addActionListener(this);
bPow.addActionListener(this);
bNull.addActionListener(this);
p1.setLayout(new?GridLayout(4,4,5,5));//網(wǎng)格布局管理器,把容器根據(jù)行數(shù)和列數(shù)分成同樣大小的單元,
//每個(gè)單元可容納一個(gè)組件,并且此組件會(huì)填滿網(wǎng)格單元,不能控
//制其占據(jù)網(wǎng)格的大小。4、4為網(wǎng)格的行、列數(shù)。5、5為組建之間的
//間距
p2.setLayout(new?FlowLayout());//用FlowLayout布局管理器將組建默認(rèn)劇中排放,默認(rèn)間隙為5個(gè)像素
add(t,"North");??????//frame的north放置輸入框,panel放置在center和south
add(p1,"Center");//將p1添加到Center中
add(p2,"South");//將p2添加到South中
setLocation(400,200);//設(shè)計(jì)按鈕尺寸
setSize(200,200);//設(shè)計(jì)窗口尺寸
setBackground(new?Color(20,200,10));//設(shè)置Frame的背景,默認(rèn)為白色
setVisible(true);//設(shè)置Frame設(shè)置為可見
addWindowListener(new?WindowAdapter(){???//關(guān)閉窗口功能
public?void?windowClosing(WindowEvent?e)
{
System.exit(0);
}
});
}
//實(shí)現(xiàn)接口ActionListener
public?void?actionPerformed(ActionEvent?e)
{
Button?temp=(Button)e.getSource();
if(e.getActionCommand().equals("number"))
{
if(first)
{
str1=str1+temp.getLabel();
t.setText(str1);//將輸入的str1顯示在文本框中
}
else
{
str2=str2+temp.getLabel();
t.setText(str2);//將輸入的str2顯示在文本框中
}
}
else?if(e.getActionCommand().equals("oper"))
{
if(str1=="")????//如果還沒有輸入數(shù)就點(diǎn)擊運(yùn)算符執(zhí)行if
{
countOper=0;//若此,則將計(jì)數(shù)清零
first=true;
}
else
{
countOper++;//計(jì)算輸入符號(hào)的個(gè)數(shù)
if(countOper1)//若輸入的符號(hào)個(gè)數(shù)多余一個(gè),則可以進(jìn)行計(jì)算
{
getResult();
}
operator=temp.getLabel();//存放加減乘除以及開方、平方的符號(hào)
first=false;
}
}
else?if(e.getActionCommand().equals("開方"))
{
double?d=Math.sqrt(Double.parseDouble(str1));
str1=String.valueOf(d);//將計(jì)算出來的結(jié)果再次傳給str1,為連計(jì)算準(zhǔn)備
t.setText(String.valueOf(d));//將計(jì)算出來的結(jié)果傳至文本框中
first=false;//置為false,即已輸入第一個(gè)數(shù)
}
else?if(e.getActionCommand().equals("平方"))
{
double?f=Math.pow(Double.parseDouble(str1),2);
str1=String.valueOf(f);
t.setText(String.valueOf(f));
first=false;
}
else?if(e.getActionCommand().equals("清除"))
{
str1="";//清空
str2="";
t.setText("");//將文本框清空
countOper=0;//將按鍵計(jì)數(shù)器清零
first=true;
error=false;
}
else?if(e.getActionCommand().equals("等於"))
{
if((str1=="")||(str2==""))???//兩個(gè)數(shù)沒有輸全就點(diǎn)擊等號(hào),執(zhí)行if
{
countOper=0;//將按鍵計(jì)數(shù)器清零
first=true;
}
else
{
getResult();
countOper=0;
}
}
}
//運(yùn)算結(jié)果的方法
public?void?getResult()
{
num1=Double.parseDouble(str1);
num2=Double.parseDouble(str2);
if(operator.equals("加"))
{
result=num1+num2;
}
else?if(operator.equals("減"))
{
result=num1-num2;
}
else?if(operator.equals("乘以"))
{
result=num1*num2;
}
else?if(operator.equals("除以"))
{
if(num2==0.0)????//除數(shù)為0的處理方法
{
error=true;
}
else
{
result=num1/num2;
}
}
if(error)
{
t.setText("error");
}
else
{
t.setText(String.valueOf(result));
str1=String.valueOf(result);??//運(yùn)算后把結(jié)果放入str1中,str2清空,為連加連減等操作做準(zhǔn)備
str2="";
}
}
//主方法
public?static?void?main(String[]?args)
{
new?Counter();//創(chuàng)建一個(gè)對(duì)象"計(jì)算器"
}
}
import???java.awt.*;
import???java.awt.event.*;
import???javax.swing.*;
class???CalculatorPanel???extends???JPanel
implements???ActionListener
{?????public???CalculatorPanel()
{?????setLayout(new???BorderLayout());
display???=???new???JTextField("0");
display.setEditable(false);
add(display,???"North");
JPanel???p???=???new???JPanel();
p.setLayout(new???GridLayout(4,???4));
String???buttons???=???"789/456*123-0.=+";
for???(int???i???=???0;???i??????buttons.length();???i++)
addButton(p,???buttons.substring(i,???i???+???1));
add(p,???"Center");
}
private???void???addButton(Container???c,???String???s)
{?????JButton???b???=???new???JButton(s);
c.add(b);
b.addActionListener(this);
}
public???void???actionPerformed(ActionEvent???evt)
{?????String???s???=???evt.getActionCommand();
if???('0'???=???s.charAt(0)??????s.charAt(0)???=???'9'
||???s.equals("."))
{?????if???(start)???display.setText(s);
else???display.setText(display.getText()???+???s);
start???=???false;
}
else
{?????if???(start)
{?????if???(s.equals("-"))
{???display.setText(s);???start???=???false;???}
else???op???=???s;
}
else
{?????calculate(Double.parseDouble(display.getText()));
op???=???s;
start???=???true;
}
}
}
public???void???calculate(double???n)
{?????if???(op.equals("+"))???arg???+=???n;
else???if???(op.equals("-"))???arg???-=???n;
else???if???(op.equals("*"))???arg???*=???n;
else???if???(op.equals("/"))???arg???/=???n;
else???if???(op.equals("="))???arg???=???n;
display.setText(""???+???arg);
}
private???JTextField???display;
private???double???arg???=???0;
private???String???op???=???"=";
private???boolean???start???=???true;
}
public???class???CalculatorApplet???extends???JApplet
{?????public???void???init()
{?????Container???contentPane???=???getContentPane();
contentPane.add(new???CalculatorPanel());
}
}
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;
/**
* 我的計(jì)算器。Cheshi 繼承于 JFrame,是計(jì)算器的界面
c*/
public class Cheshi extends JFrame {
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 Cheshi(String title) throws HeadlessException {
super(title); // 調(diào)用父類構(gòu)造方法
setupFrame(); // 調(diào)整窗體屬性
setupControls(); // 創(chuàng)建控件
}
private void setupControls() {
setupDisplayPanel(); // 創(chuàng)建文本面板
setupButtonsPanel(); // 創(chuàng)建按鈕面板
}
// 創(chuàng)建按鈕面板并添加按鈕
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", "*", "", // 空字符串表示這個(gè)位置沒有按鈕
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上創(chuàng)建按鈕
*
* @param panel 要?jiǎng)?chuàng)建按鈕的面板
* @param labels 按鈕文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 為空,則表示創(chuàng)建一個(gè)空面板。否則創(chuàng)建一個(gè)按鈕。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener); // 為按鈕添加偵聽器
panel.add(b);
}
}
}
// 設(shè)置顯示面板,用一個(gè)文本框來作為計(jì)算器的顯示部分。
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);
}
// 調(diào)整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右對(duì)齊
textbox.setEditable(false); // 文本框只讀
textbox.setBackground(Color.white); // 文本框背景色為白色
}
// 調(diào)整窗體
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 當(dāng)窗體關(guān)閉時(shí)程序結(jié)束
this.setLocation(100, 50); // 設(shè)置窗體顯示在桌面上的位置
this.setSize(300, 200); // 設(shè)置窗體大小
this.setResizable(false); // 窗體大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Cheshi frame = new Cheshi("我的計(jì)算器");
frame.setVisible(true); // 在桌面上顯示窗體
}
}
/**
* 計(jì)算器核心邏輯。這個(gè)邏輯只能處理 1~2 個(gè)數(shù)的運(yùn)算。
*/
class CalculatorCore {
private String displayText = "0"; // 要顯示的文本
boolean reset = true;
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);
}
});
}
// 根據(jù)命令處理。這里的命令實(shí)際上就是按鈕文本。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 當(dāng)按下 CE 時(shí)
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 當(dāng)按下 C 時(shí),將計(jì)算器置為初始狀態(tài)。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 當(dāng)按下 = 時(shí)
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 計(jì)算結(jié)果
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
}
}
// 當(dāng)按下 +-*/ 時(shí)(這里也可以擴(kuò)展成其他中間操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 當(dāng)按下 . 時(shí)
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText += ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 當(dāng)按下 0-9 時(shí)
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
displayText += command;
}
reset = false;
}
// 運(yùn)算符處理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按鈕處理接口
interface Processor {
void calculate(String command);
}
}
我這個(gè)程序可以實(shí)現(xiàn)加減乘除求余等功能,界面化操作,簡(jiǎn)單好看,希望對(duì)你有用!
import java.awt.*;
import java.awt.event.*;
import java.lang.StrictMath;
public class AddMyFrame extends Frame{
TextField t1,t2,t3;
Label l2;
Choice ch = new Choice();
Button b1;
public AddMyFrame(String str){
super(str);
setBackground(Color.gray);
setLayout(new FlowLayout());
setSize(400,150);
addWindowListener(new WindowAdapter(){
public void windowClosed(WindowEvent e){
System.exit(0);
}
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
initFrame();
}
public void initFrame(){
t1=new TextField(6);
t2=new TextField(6);
t3=new TextField(7);
ch.add("+");
ch.add("-");
ch.add("*");
ch.add("/");
ch.add("%");
ch.add("Sqrt");
l2=new Label("=");
b1=new Button("確定");
ButtonEvent be=new ButtonEvent();
t1.addKeyListener(be);
add(t1);
add(ch);
t2.addKeyListener(be);
add(t2);
add(l2);
add(t3);
b1.addActionListener(be);
add(b1);
}
public static void main(String [] atg){
AddMyFrame m1=new AddMyFrame("常用計(jì)算器");
m1.setVisible(true);
}
//------------------------------------------------
class ButtonEvent extends KeyAdapter implements ActionListener{
public void actionPerformed(ActionEvent e){
addMethod();
}
public void addMethod(){
int t1Value=0;
int t2Value=0;
double t3Value=0;
try{
t1Value=Integer.parseInt(t1.getText());
}catch(Exception ex){
t1Value=0;
t1.setText("0");
}
try{
t2Value=Integer.parseInt(t2.getText());
}catch(Exception ex){
t2Value=0;
t2.setText("0");
}
if(ch.getSelectedItem()==("+")){
t3Value=t1Value+t2Value;
t3.setText(String.valueOf(t3Value));
}
else if(ch.getSelectedItem()==("-")){
t3Value=t1Value-t2Value;
t3.setText(String.valueOf(t3Value));
}
else if(ch.getSelectedItem()==("*")){
t3Value=t1Value*t2Value;
t3.setText(String.valueOf(t3Value));
}
else if(ch.getSelectedItem()==("/")){
t3Value=t1Value/t2Value;
t3.setText(String.valueOf(t3Value));
}
else if(ch.getSelectedItem()==("%")){
t3Value=t1Value%t2Value;
t3.setText(String.valueOf(t3Value));
}
else if(ch.getSelectedItem()==("Sqrt")){
t3Value=t1Value*t2Value;
t3Value=Math.sqrt(t3Value);
t3.setText(String.valueOf(t3Value));
}
}
public void keyReleased(KeyEvent e){
addMethod();
}
}
}
//常用計(jì)算器版權(quán)@playlong2009先生2009/12/5
學(xué)java的時(shí)候自己編的,很簡(jiǎn)單,能夠連續(xù)輸入計(jì)算式后進(jìn)行計(jì)算
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**簡(jiǎn)易計(jì)算器,能夠進(jìn)行簡(jiǎn)單的計(jì)算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存結(jié)果
StringBuilder sb = new StringBuilder();//保存要進(jìn)行的計(jì)算式
int x = 0; //用來判斷上一次的事件類型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存計(jì)算式,通過方法進(jìn)行運(yùn)算
public CalculatorA(){
frame = new JFrame("我的計(jì)算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//設(shè)置輸入字體
public void setFondAndColor(){
field.setFont(new Font("宋體",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//設(shè)置字體從右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得當(dāng)前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //當(dāng)x為0時(shí)表示還沒有進(jìn)行輸入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
else if(x == 2){
field.setText("數(shù)據(jù)格式錯(cuò)誤.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的數(shù)據(jù)格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//對(duì)數(shù)字字符串進(jìn)行排除不必要符號(hào)
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
import java.util.*;
public class Admin {//管理類
Scanner in=new Scanner(System.in);
String msg="\t編號(hào)\t姓名\t年齡\tJava\tC#\tHtml\tSql\t總分\t平均分";
public void print(Student[] arr){//輸出方法
System.out.println(msg);
for(int i=0;iarr.length;i++){
if(arr[i]!=null){
arr[i].setSum();
arr[i].setAvg();
System.out.println(arr[i]);
}
}
}
public boolean exist(int num,Student stu){//判斷存在方法
if(stu!=null){
if(stu.getNum()==num){
return true;
}else{
return false;
}
}
return false;
}
public void create(String name,int age,Student[] arr){//添加方法
Student stu=new Student();
stu.setName(name);
stu.setAge(age);
int i=this.setIndex(arr);
stu.setNum(i);
if(i==9999){
System.out.println("添加學(xué)生人數(shù)已達(dá)到上限,不能再添加了!");
}else{
arr[i]=stu;
}
this.print(arr);
}
public int setIndex(Student[] arr){// 返回下標(biāo)
for(int i=0;iarr.length;i++){
if(arr[i]==null){
return i;
}
}
return 9999;
}
public void select(int num,Student[] arr){//查找方法
System.out.println(msg);
for(int i=0;iarr.length;i++){
/*if(arr[i]!=null){
if(arr[i].getNum()==num){
System.out.println(arr[i]);
return;
}
}*/
if(this.exist(num, arr[i])){
System.out.println(arr[i]);
return;
}
}
System.out.println("\t---!沒有這個(gè)學(xué)生的存在!---\t");
}
public void update(int num,Student[] arr){//更新方法
for(int i=0;iarr.length;i++){
if(this.exist(num, arr[i])){
System.out.println("請(qǐng)輸入修改的姓名:");
arr[i].setName(in.next());
System.out.println("請(qǐng)輸入修改的年齡:");
arr[i].setAge(in.nextInt());
System.out.println("---更新信息成功---");
this.print(arr);
return;
}
}
System.out.println("---更新信息失敗---");
}
public void delete(int num,Student[] arr){//刪除方法
for(int i=0;iarr.length;i++){
if(this.exist(num, arr[i])){
arr[i]=null;
System.out.println("---刪除信息成功---");
this.print(arr);
return;
}
}
System.out.println("---刪除信息失敗---");
}
public void input(int num,Student[] arr){//輸入方法
for(int i=0;iarr.length;i++){
if(this.exist(num, arr[i])){
System.out.println("請(qǐng)輸入"+arr[i].getName()+"學(xué)生的java成績(jī):");
if(in.hasNextInt()){
arr[i].setJava(in.nextInt());
}
//arr[i].setJava(in.nextInt());
System.out.println("請(qǐng)輸入"+arr[i].getName()+"學(xué)生的c_sharp成績(jī):");
if(in.hasNextInt()){
arr[i].setC_sharp(in.nextInt());
}
//arr[i].setC_sharp(in.nextInt());
System.out.println("請(qǐng)輸入"+arr[i].getName()+"學(xué)生的html成績(jī):");
if(in.hasNextInt()){
arr[i].setHtml(in.nextInt());
}
//arr[i].setHtml(in.nextInt());
System.out.println("請(qǐng)輸入"+arr[i].getName()+"學(xué)生的sql成績(jī):");
if(in.hasNextInt()){
arr[i].setSql(in.nextInt());
}
//arr[i].setSql(in.nextInt());
this.print(arr);
break;
}
}
}
public void couseSort(int num,Student[] arr){//學(xué)科排序方法
if(num==1){
for(int i=0;iarr.length-1;i++){
for(int j=i+1;jarr.length;j++){
if(arr[i]!=nullarr[j]!=null){
if(arr[i].getJava()arr[j].getJava()){
Student t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
}else if(num==2){
for(int i=0;iarr.length;i++){
for(int j=i+1;jarr.length;j++){
if(arr[i]!=nullarr[j]!=null){
if(arr[i].getC_sharp()arr[j].getC_sharp()){
Student t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
}else if(num==3){
for(int i=0;iarr.length;i++){
for(int j=i+1;jarr.length;j++){
if(arr[i]!=nullarr[j]!=null){
if(arr[i].getHtml()arr[j].getHtml()){
Student t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
}else if(num==4){
for(int i=0;iarr.length;i++){
for(int j=i+1;jarr.length;j++){
if(arr[i]!=nullarr[j]!=null){
if(arr[i].getSql()arr[j].getSql()){
Student t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
}
this.print(arr);
}
public void sumSort(Student[] arr){//總分排序方法
for(int i=0;iarr.length;i++){
for(int j=i+1;jarr.length;j++){
if(arr[i]!=nullarr[j]!=null){
if(arr[i].getSum()arr[j].getSum()){
Student t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
this.print(arr);
}
}
public class Student {//學(xué)生類
private int num;
private String name;
private int age;
private int java;
private int c_sharp;
private int html;
private int sql;
private int sum;
private double avg;
public int getNum(){
return num;
}
public void setNum(int num){
this.num=num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getJava() {
return java;
}
public void setJava(int java) {
this.java = java;
}
public int getC_sharp() {
return c_sharp;
}
public void setC_sharp(int c_sharp) {
this.c_sharp = c_sharp;
}
public int getHtml() {
return html;
}
public void setHtml(int html) {
this.html = html;
}
public int getSql() {
return sql;
}
public void setSql(int sql) {
this.sql = sql;
}
public int getSum() {
return sum;
}
public void setSum() {
this.sum =this.java+this.c_sharp+this.html+this.sql;
}
public double getAvg() {
return avg;
}
public void setAvg() {
this.avg = this.sum/4;
}
public String toString(){
String msg="\t"+this.num+"\t"+this.name+"\t"+this.age+"\t"+this.java+"\t"+this.c_sharp+"\t"+this.html+"\t"+this.sql+"\t"+this.sum+"\t"+this.avg+"\t";
return msg;
}
}
import java.util.*;
public class Main {//主
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("---請(qǐng)定義學(xué)生的人數(shù)---");
Student[] stuArr=new Student[in.nextInt()];
Admin adminStu=new Admin();
while(true){
System.out.println("---選擇你要執(zhí)行的功能---");
System.out.println("0:添加一個(gè)學(xué)生");
System.out.println("1:查找一個(gè)學(xué)生");
System.out.println("2:根據(jù)編號(hào)更新信息");
System.out.println("3:根據(jù)編號(hào)刪除學(xué)生");
System.out.println("4:根據(jù)編號(hào)輸入成績(jī)");
System.out.println("5:根據(jù)某門學(xué)科排序");
System.out.println("6:根據(jù)總分進(jìn)行排序");
System.out.println("7:退出系統(tǒng)");
//int number =in.nextInt();//判斷
String opt=in.next();
if(opt.equals("0")){
System.out.println("---執(zhí)行添加方法---");
System.out.println("請(qǐng)輸入學(xué)生的姓名:");
String name=in.next();
System.out.println("請(qǐng)輸入學(xué)生的年齡:");
int age=in.nextInt();
adminStu.create(name,age,stuArr);
//adminStu.print(stuArr);
}else if(opt.equals("1")){
System.out.println("---執(zhí)行查找方法---");
System.out.println("請(qǐng)輸入學(xué)生的編號(hào):");
int num=in.nextInt();
adminStu.select(num, stuArr);
}else if(opt.equals("2")){
System.out.println("---執(zhí)行更新方法---");
System.out.println("請(qǐng)輸入學(xué)生的編號(hào):");
int num=in.nextInt();
/*System.out.println("請(qǐng)輸入修改的姓名:");
String name=in.next();
System.out.println("請(qǐng)輸入修改的年齡:");
int age=in.nextInt();*/
adminStu.update(num, stuArr);
//adminStu.print(stuArr);
}else if(opt.equals("3")){
System.out.println("---執(zhí)行刪除方法---");
System.out.println("請(qǐng)輸入學(xué)生的編號(hào):");
int num=in.nextInt();
adminStu.delete(num, stuArr);
//adminStu.print(stuArr);
} else if(opt.equals("4")){
System.out.println("---執(zhí)行輸入方法---");
System.out.println("請(qǐng)輸入學(xué)生的編號(hào):");
int num=in.nextInt();
adminStu.input(num, stuArr);
}else if(opt.equals("5")){
System.out.println("---執(zhí)行學(xué)科排序方法---");
System.out.println("請(qǐng)選擇需排序的學(xué)科:1.java、2.c_sharp、3.html、4.sql");
int num=in.nextInt();
adminStu.couseSort(num, stuArr);
}else if(opt.equals("6")){
System.out.println("---執(zhí)行總分排序方法---");
adminStu.sumSort(stuArr);
}else if(opt.equals("7")){
System.out.println("--程序已退出--");
//break;//退出循環(huán)
System.exit(0);//退出程序
}
}
}
}
這是我以前編寫的一個(gè)微型學(xué)生管理系統(tǒng),希望可以給你點(diǎn)思路。休息時(shí)間不多就懶。
第一題: 元素的復(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ù)制元素,?左開右閉區(qū)間[0,5)
System.out.println(Arrays.toString(newScores));//調(diào)用數(shù)組工具類的方法轉(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ù)的無序集合
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.,如果沒有使用標(biāo)記為false,
例如 隨機(jī)產(chǎn)生了一個(gè)下標(biāo)0 ?,那么查看flags[0] ,如果是true, 那么說明該元素已經(jīng)使用了,重新產(chǎn)生一個(gè)隨機(jī)數(shù), 如果是false ,那么表示nums[0]沒有被使用
具體代碼如下(稍微留個(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?,表示全部沒有使用過
//用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));
}
}